Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top