MongoDB Update array element

I have a document structure like

{ "_id" : ObjectId("52263922f5ebf05115bf550e"), "Fields" : [ { "Field" : "Lot No", "Rules" : [ ] }, { "Field" : "RMA No", "Rules" : [ ] } ] } 

I tried updating using the following code to insert into an array of rules that will contain objects.

 db.test.update({ "Fields.Field":{$in:["Lot No"]} }, { $addToSet: { "Fields.Field.$.Rules": { "item_name": "my_item_two", "price": 1 } } }, false, true); 

But I get the following error:

cannot join array using string field name [Field]

How to make an update?

+4
source share
1 answer

You've gone too deep with this $ template. You map an element in the Fields array to access it with: Fields.$ . This expression returns the first match in your Fields array, so you reach its Fields.$.Field or Fields.$.Result fields.

Now let's update update :

 db.test.update({ "Fields.Field": "Lot No" }, { $addToSet: { "Fields.$.Rules": { 'item_name': "my_item_two", 'price':1 } } }, false, true); 

Note that I abbreviated query as it is equal to your expression.

+4
source

Source: https://habr.com/ru/post/1500379/


All Articles