1

I want to update an array that I have in a mongo doc. The structure of which looks something like:

{
  _id: id,
  myArray: [
    {key1: val, key2: val, key3: val}, 
    {key1: val, key2: val, key3: val}, 
    {key1: val, key2: val, key3: val}
  ]
}

I need to be able to do something like the SQL equivalent of update WHERE. Namely, get this particular document in the collection by searching with id (which you can do trivially with MyDoc.update({_id: id}...);) and then locate the specific object in the array based on a key value pair, and then update the value of a different key in that same object.

1 Answer 1

3

When mongodb queries an array field it provides a positional operator $ which you can use to access a specific element in that array. You can use an elemMatch operator to search into the fields within an array of objects.

Example:

db.myCollection.find({
   _id: ObjectId("53b1a44350f148976b0b6044"),
   myArray: {
      $elemMatch: {key1: 'somevalue'}
   }
}, {
   $set:{
      'myArray.$.key2': 'someOtherValue'
   }
});

See: http://docs.mongodb.org/manual/reference/operator/update/positional/

Sign up to request clarification or add additional context in comments.

4 Comments

Yeah, I understand that, but I have a bunch of different docs in that collection, so first I need to specify by id, as noted in the question ("get this particular document in the collection by searching with id"). The problem is I can't both specify by id and then use $elemMatch in the first argument of find or update .
Yes you can actually. Specifying and _id for the document, and an elemMatch for the sub-document will work just fine. It'll find the document, then it'll query into the sub-document, and allow a positional operator in your update object. The example was to show how to query into sub-documents. I will update my example.
The queries are boolean, so imagine they are separated by an and operator. So the example reads like "Find this _id AND a sub-document". Therefore you can indeed pass an both an _id and then use an $elemMatch, as they don't contradict eachother.
Hey, it turned out my problem was meteor specific, I had the mongo syntax correct from the start. Thanks for your help though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.