Home Mongodb .net updating one of the embedded documents
Reply: 2

Mongodb .net updating one of the embedded documents

dabishan
1#
dabishan Published in 2017-11-15 02:06:49Z

I have an orders and each has transactions embedded.

{
    _id: orderId1,
    other_fields: something else,
    transactions: [
       {
           _id: someId,
           price: 25,
           status: 1
       },
       {
           _id: someId2,
           price: 30,
           status: 0
       }
    ]
}

Now i want to change the status of one of the transactions(lets say: someId2). How can i do that?

Both orders and transactions are models with transaction as ICollection<Transaction>

Also, is it possible without using any magic string?

Clement Amarnath
2#
Clement Amarnath Reply to 2017-11-15 13:07:23Z

This can be done using the below query

db.collection.update({"transactions._id":"someId2"}, {$set:{"transactions.$.status":2}})

First part of the query is to find the record and the second part is to update the document, this update is positional update

Please note that positional update will be done for only one matching document. Even if we have multiple documents matching the query only one document will be updated, so to safely use the positional update give the maximum condition in find part of the query to retrieve the unique matching document, say in this case the modified query is

db.collection.update({"_id":"orderId1", "transactions._id":"someId2"}, {$set:{"transactions.$.status":1}})
Kirk Larkin
3#
Kirk Larkin Reply to 2017-11-15 13:37:33Z

Here's an example of one way this can be done using the C# driver:

await mongoCollection.UpdateOneAsync(
    o => o.Id == orderId1 && x.Transactions.Any(t => t.Id == someId2),
    Builders<Order>.Update.Set(x => x.Transactions[-1].Status, someStatus));

The use of -1 as an indexer is the key to all of this - it's essentially the translation from C# to the Positional Operator. This instructs the driver to use the index that was matched in the call to x.Transactions.Any in my example. I'm sure there are alternatives to using Any, but given that you're searching by a unique ID, this should work for your setup.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.381906 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO