3

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.

sunilkumarba
  • 851
  • 2
  • 9
  • 18

2 Answers2

4

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?

Robert Stam
  • 12,039
  • 2
  • 39
  • 36
  • Thanks for the answer. In reality, this is not the query I use. For keeping the question simple, the query was based on the city. – sunilkumarba Feb 22 '12 at 08:38
2

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);
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134