Reputation: 25050
I'd like to upsert json document as below code;
string CollectionName = "Collection";
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(MongoDbConnectionString)
);
settings.SslSettings =
new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
var mongoClient = new MongoClient(settings);
var db = mongoClient.GetDatabase(MongoDbDatabaseName);
var collection = db.GetCollection<BsonDocument>(CollectionName);
// id that I want to set.
var id = Guid.NewGuid().ToString();
var _id = Guid.NewGuid().ToString();
JObject jObject = new JObject(
new JProperty("id", id), // Id test 1
new JProperty("_id", _id), // Id test 2
new JProperty("property1", "value1"),
new JProperty("property2", "value2"));
BsonDocument newDoc = BsonDocument.Parse(jObject.ToString());
// upsert reference: http://stackoverflow.com/q/7240028/361100
var result = collection.ReplaceOne(
filter: new BsonDocument("id", jObject["id"].Value<string>()),
options: new UpdateOptions { IsUpsert = true },
replacement: newDoc);
The id
is the value I want to set manually, but the result is as below;
{
"$id": "0106669b-9670-4547-a2a3-f7ea800fac0d", // Id test 1
"_id": "9eb71b3e-83be-4dd9-b037-269d59cbe5e4", // Id test 2
"id": "9a0a4b90-5be7-44b7-af05-e3bbe08dc25e", // system generated
"property1": "value1",
"property2": "value2",
"_rid": "I2ECAKbBewAEAAAAAAAAAA==",
"_self": "dbs/I2ECAA==/colls/I2ECAKbBewA=/docs/I2ECAKbBewAEAAAAAAAAAA==/",
"_etag": "\"0000d277-0000-0000-0000-590c557a0000\"",
"_attachments": "attachments/",
"_ts": 1493980531
}
My id
value is placed in $id
property which is not I expected, and the property id
in document is generated by the system.
NOTE
I tested both id
and _id
but all of them are not set as DocumentDB "id"
.
DocumentDB .NET library allows to set id
by myself if I only put the property name id
. How to do it with MongoDB .NET driver?
Upvotes: 1
Views: 655
Reputation: 226
In MongoDB, the id of the document is "_id" and not "id". To get the expected behavior, you need to add a new JProperty with name == "_id".
JObject jObject = new JObject(
new JProperty("_id", id),
new JProperty("id", id),
new JProperty("property1", "value1"),
new JProperty("property2", "value2"));
Upvotes: 1