1

I have this collection in MongoDB (version v3.6.3):

{
  _id: '1'
  elements:[
    {
      _id: '11'
      status : DRAFT   
    },
    {
      _id: '12'
      status : DRAFT   
    }
  ]
}

I would like to update the element 11 from job 1 ONLY IF the status is DRAFT. I've tried this query:

db.getCollection('jobs').update(
  {'_id':'1', 'elements._id': '11', 'elements.status': 'DRAFT'},
  {'$set': { 'elements.$.status' : 'APPROVED' } }
)

and as result I have:

ambiguous positional update operation

what is the problem?


SOLUTION (thanks @neil-lun)

db.getCollection('jobs').update({
  '_id':'1', 
  'elements': {
    '$elemMatch': {
      '_id': '11', 
      'elements.status': 'DRAFT'
    }
  }
},
{'$set': { 'elements.$.status' : 'APPROVED' } })

What confused me is that:

db.getCollection('jobs').find({
  '_id':'1', 'elements._id': '11', 'elements.status': 'DRAFT'})

is a valid query and works fine

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Luca
  • 105
  • 1
  • 1
  • 7
  • Are you using mongo shell? The _id and element_id are int in documents but passed as a string in the update query. – Atish May 27 '18 at 17:22
  • @Astro I'm using mongo shell and all my _id are strings – Luca May 27 '18 at 20:52
  • @Ashish it works fine if i remove one of the conditions on the `elements`, but I need them – Luca May 27 '18 at 20:55
  • `$elemMatch` is required in order to match "multiple" criteria for array elements. The error is because your conditions match "possibly different" elements of the array by the "dot notation" used. See also [Specify Multiple Conditions for Array Documents](https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#specify-multiple-conditions-for-array-of-documents) in the core documentation. – Neil Lunn May 27 '18 at 22:17
  • Then try with `elemMatch` – Ashh May 28 '18 at 01:47

0 Answers0