Re: Updating a specific mongodb value using the offical c# driver

197 views
Skip to first unread message

Andre de Frere

unread,
Oct 8, 2012, 12:50:41 AM10/8/12
to mongod...@googlegroups.com
Hi,

Not sure which ways you were trying to update using .update() and .add(), but .update() is one way to get your the outcome you are looking for.

You could use an update command directly:

var query = new QueryDocument {
    { "geolocationPresent", "Yes" }
};
var update = new UpdateDocument {
{ "$set", new BsonDocument("geolocationPresent", "Checked") }
};
collection.Update(query, update);

or by using a Query builder (available when using MongoDB.Driver.Builders)

var query = Query.EQ("geolocationPresent", "Yes");
var update = Update.Set("geolocationPresent", "Checked");
collection.update(query, update);

Both of the above snippets will set all of the documents with {geolocationPresent : "Yes"} to {geolocationPresent : "Checked"} without changing the values of other fields in those documents (or removing them).

Let me know if this helps,
André

Andre de Frere

unread,
Oct 8, 2012, 1:10:45 AM10/8/12
to mongod...@googlegroups.com
Hi,

Apologies, I was intending to include in my answer a method of saving each document in turn (rather than the whole collection at the same time).

You could use something like the following to update each document in turn as you iterate through the collection:

foreach (BsonDocument item in collection.Find(query)) 

BsonElement geolocationPresent = item.GetElement("geolocationPresent"); 
geolocationPresent.Value = "Checked";
item.SetElement(geolocationPresent);
collection.Save(item);
}

Hopefully this is helpful to you,
André
Reply all
Reply to author
Forward
0 new messages