Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use MongoDB's Postional Operator in C# code?

I want to use the positional operator of the MongoDB in C# code. Here is data structure for Customer:

{ 
  name:"Robert", 
  age:40, 
  addresses:[ 
    {street:"...", city:"New York", country:"USA", ...}, 
    {street:"...", city:"California", country:"USA", ...},
  ],
}

So, if I want to update the street value where the address if of New York city, I use this query in MongoDB:

db.customer.update(
   { "addresses.city" : "New York"}, 
   { $set : {
       "addresses.$" : {"street":"New street", city:"New York", country:"USA",...}
   } }, false, true);

What is the equivalent query to use in C# code? How to use the positional operator in C# code?

I'm using the official MongoDB driver.

like image 588
sunilkumarba Avatar asked Dec 04 '25 02:12

sunilkumarba


2 Answers

You would write that in C# like this:

var newAddress = new BsonDocument
{
    { "street", "New street" },
    { "city", "New York" },
    { "country", "USA" }
    // ...
};
var query = Query.EQ("addresses.city", "New York");
var update = Update.Set("addresses.$", newAddress);
var result = customerCollection.Update(query, update, UpdateFlags.Multi);

That does seem like a dangerous update to make; you're overwriting a street address based only on the city matching? Is the query working correctly in the mongo shell?

like image 65
Robert Stam Avatar answered Dec 05 '25 14:12

Robert Stam


Positional operator is internal thing of mongodb atomic updates, so there is no difference for simple atomic update and update with positional operator.

Equivalent of above mongo shell syntax at c# would be:

var collection = database.GetCollection<Customer>("customer");
var searchQuery = Query.EQ("addresses.city", "New York");
var address = new Address()
{
  street = "New street",
  city = "New York",
  country = "USA"
};
var update = Update.Set("addresses.$", address.ToBsonDocument())
collection.Update(searchQuery, update, UpdateFlags.Multi);
like image 22
Andrew Orsich Avatar answered Dec 05 '25 16:12

Andrew Orsich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!