Reputation: 1772
Suppose I have the following documents inside a collection:
[{ id:1, items: [1, 4, 1], flag:false},
{ id:2, items: [3, 1, 3], flag:false },
{ id:3, items: [2, 4, 6], flag:false },
{ id:4, items: [8, 7, 2], flag:false }]
I am required to Set flag
to true
if items[1] == 4
.
So, the state of the collection after the update would be:
{ id:1, items: [1, 4, 1], flag:true},
{ id:2, items: [3, 1, 3], flag:false },
{ id:3, items: [2, 4, 6], flag:true},
{ id:4, items: [8, 7, 2], flag:false }
How do I do this using the C#
driver?
Thanks!
Upvotes: 3
Views: 2117
Reputation: 2305
If you are using the second version of MongoDB.Driver (2.0.0-beta2) you can do this:
var client = new MongoClient(connectionString);
var database = client.GetDatabase("test");
var collection = database.GetCollection<Entity>("entities");
await collection.UpdateManyAsync(
filter => filter.Items[1] == 4,
update => update.Set(ent => ent.Flag, true));
Assuming you have Entity class:
public class Entity
{
public int Id { get; set; }
public List<int> Items { get; set; }
public bool Flag { get; set; }
}
Upvotes: 5
Reputation: 6371
Use this query to do the update via mongo shell
db.test.update({'items.1' : 4}, { $set : { flag : true}}, {multi : true})
The C# code would be:
var url = new MongoUrl("mongodb://localhost:27017");
var client = new MongoClient(url);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection("test");
var query = Query.EQ("items.1", 4);
var update = Update.Set("flag", true);
collection.Update(query, update, UpdateFlags.Multi);
Upvotes: 3