Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a MongoDB Collection of Documents that has an imbedded collection of documents as an array. I want to find and update a specific member of that array if certain values exist in the array member document.

I can find the array member without issue(the Query Document works perfectly), but when I try to $set the member with the new/updated values, the first member is always set, rather than the member that I found.

How can I update the same array member that I found, rather than the first item in the array. Here is what I am currently doing, where 'InventoryData' is the name of the embedded array, and the InventoryRecord is the updated member that contains the value my query is matching on successfully:

Here is the query that successfully finds the matching array member:
C#
query = new QueryDocument { { "_id", BTKey }, { "InventoryData.WarehouseCode", InventoryRecord.WarehouseCode }, { "InventoryData.InventoryType", InventoryRecord.InventoryType }, { "InventoryData.CustomerNumber", InventoryRecord.CustomerNumber }

Then, here is where I try to update that member using .$ :

C#
var update2 = MongoDB.Driver.Builders.Update.Set("InventoryData.$", InventoryRecord.ToBsonDocument());

MongoConnection.Products.Update(query, update2, UpdateFlags.None);

...but the first item in the array is always updated, rather than the target item.

Any help will be greatly appreciated, thanks.
Posted
Updated 8-May-15 12:00pm
v2

1 solution

Use $elemMatch to select a single embeded document using all queries.
see the differnce in the following links

1. http://docs.mongodb.org/manual/tutorial/query-documents/#specify-multiple-criteria-for-array-of-documents[^]
2. http://docs.mongodb.org/manual/tutorial/query-documents/#id4[^]

So you are selecting multple document and and updating the firstone.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900