I am trying to use c# to insert each new subdocument into an array at the top position using driver version 2.4.2. In mongo the following command works well:
db.getCollection('Operation').update(
{_id: ObjectId('586e9ec5ab3d05173cd88957') },
{$push: {'location': {$each: [ { 'value' : 'Site', 'time' : ISODate('2017-02-24T16:05:44.204Z'), 'user' : 'user1' } ], $position: 0 } } }
)
Then the result is:
{
"_id" : ObjectId("586e9ec5ab3d05173cd88957"),
"location" : [
{
"value" : "Site",
"time" : ISODate("2017-02-24T16:05:44.204Z"),
"user" : "user1"
}
]
}
But so far I do not succeed in getting the same result in C#. I have tried so far:
var filter = Builders<BsonDocument>.Filter.Eq("_id", ObjectId.Parse("586e9ec5ab3d05173cd88957"));
var update = Builders<BsonDocument>.Update.PushEach("location", new List<BsonArray>() { new BsonArray { new BsonDocument { { "value", "Site" }, { "time", DateTime.UtcNow }, { "user", "user1" } } } }, position: 0);
collection.UpdateOne(filter, update);
And also no succes trying to specify all in text:
collection.UpdateOne("{ '_id': ObjectId('586e9ec5ab3d05173cd88957') }", "{ '$push': {'location': { '$each': [ { 'value' : 'Site', 'time' : ISODate('2017-02-24T16:05:44.204Z'), 'user' : 'user1' } ], $position: 0 } } }");
Any suggestions?
PushEach
expects just a BsonArray
parameter, not a List<BsonArray>
.
You should be doing something like
var update = updateBuilder.PushEach("location", locationBSONArray);
There is no need to serialize to bson document.
Took me a while because of a typo. The answer of user1892538 was correct. This works:
var update = Builders<BsonDocument>.Update.PushEach("location", new BsonArray { new BsonDocument { { "value", "Site" }, { "time", DateTime.UtcNow }, { "user", "user1" } } }, position: 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.