2

I have this data:

{
    "_id" : ObjectId("5956795e1729955bbed30e68"),
    "messages" : [
        {
            "text" : "Test 1"
        },
        {
            "text" : "Test 2",
            "link" : {
                "type" : "Calendar"
            }
        }
    ]
}

and I run this query:

db.collection('user').update(
    {
      '_id': ObjectID.createFromHexString('5956795e1729955bbed30e68'),
      'messages.isLocked': { $exists: false }
    },
    {
      $set: { 'messages.$.isLocked': true }
    }
);

I expect to have all messages with "isLocked: true" but I receive:

MongoError: The positional operator did not find the match needed from the query. Unexpanded update: messages.$.isLocked

Other input: if I run the query 'messages.text': { $exists: true } instead of 'messages.isLocked': { $exists: false }, Mongo update ONLY the first element -.-

What am I doing wrong about this feature?

UPDATE: I using MongoDB 3.4.5, so I think that it's possible to achieve:

It works only with the first occurence: https://docs.mongodb.com/manual/reference/operator/update/positional/

Zosma
  • 165
  • 1
  • 7
  • Possible duplicate of [How to Update Multiple Array Elements in mongodb](https://stackoverflow.com/questions/4669178/how-to-update-multiple-array-elements-in-mongodb) – Rahul Sharma Jul 11 '17 at 11:41
  • I using MongoDB 3.4.5, so I think that it's possible to achieve: https://docs.mongodb.com/manual/reference/operator/update/positional/ – Zosma Jul 11 '17 at 12:09
  • 1
    I don't see why you think it should be possible. The doc you linked to, it states in no uncertain terms: "the positional $ operator acts as a placeholder for the __first__ element [matched by the query]". At best, you'll be able to update only one sub-document, not all of them (not with the positional operator, anyway) – Sergio Tulentsev Jul 11 '17 at 12:11
  • @LucaM from the the link you shared in comments, read carefully the contents under this heading https://docs.mongodb.com/manual/reference/operator/update/positional/#update-embedded-documents-using-multiple-field-matches – Rahul Sharma Jul 11 '17 at 12:19
  • Yes, it is only the first element. The title "Update Documents in an Array" confused me. So the old for-loop solution.. not a great thing. Thanks anyway – Zosma Jul 11 '17 at 12:27

0 Answers0