'Mongo db C# add a new guid/objectid to document
how to send a query like this from the C# driver to mongodb db.getCollection("myCollection").updateMany({}, {$set:{_uniqueId : "UUID()"}}) I have tried doing this :
var pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(new BsonDocument()
{
{"$addFields", new BsonDocument(){{"_uniqueId" , new BsonDocument()
{
{"$function" , new BsonDocument()
{
{"body" , "function(){ return new UUID()}"},
{"args" , new BsonArray()},
{"lang" , "js"},
}}
}
}}}
});
var definition = Builders<BsonDocument>.Update.Pipeline(pipeline);
mongoDatabase.GetCollection<BsonDocument>(set.CollectionName).UpdateMany(Builders<BsonDocument>.Filter.Empty, definition);
but i just get and empty _uniqueId
Solution 1:[1]
I have found something that works, I will be glad if someone found a simpler solution to this.
var pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(new BsonDocument()
{
{"$addFields", new BsonDocument(){{"_uniqueId" , new BsonDocument()
{
{"$toObjectId", new BsonDocument(){
{"$function" , new BsonDocument()
{
{"body" , "function(){var id = new ObjectId(); return id.valueOf()}"},
{"args" , new BsonArray()},
{"lang" , "js"},
}}
}}
}
}}}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IdoAmar |
