【问题标题】:Azure DocumentDB with MongoDB .NET driver: how to set id manually?带有 MongoDB .NET 驱动程序的 Azure DocumentDB:如何手动设置 id?
【发布时间】:2017-05-05 11:10:07
【问题描述】:

我想将 json 文档插入如下代码;

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);

id是我要手动设置的值,结果如下;

{
  "$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
}

我的id 值放在$id 属性中,这不是我所期望的,而文档中的属性id 是由系统生成的。

注意 我测试了id_id,但它们都没有设置为DocumentDB "id"

如果我只输入属性名称id,DocumentDB .NET 库允许我自己设置id。 MongoDB .NET驱动怎么做?

【问题讨论】:

    标签: c# .net mongodb azure azure-cosmosdb


    【解决方案1】:

    在 MongoDB 中,文档的 id 是“_id”而不是“id”。要获得预期的行为,您需要添加一个名为 == "_id" 的新 JProperty。

    JObject jObject = new JObject(
        new JProperty("_id", id),
        new JProperty("id", id),
        new JProperty("property1", "value1"),
        new JProperty("property2", "value2"));
    

    https://docs.mongodb.com/manual/reference/method/db.collection.insert/#insert-a-document-specifying-an-id-field

    【讨论】:

    • 正如我所说,_id 在 DocumentDB 中不被识别为 idreal id是自动生成的。
    • @Youngjae,您是否也在使用 MongoDB 驱动程序来读取文档? “Id”是 DocumentDB 中的一个特殊属性,始终设置为“_id”的字符串表示形式。 Mongo层在存储时将用户指定的“id”转换为“$id”,但在通过MongoDB接口返回结果之前将其转换回“id”
    • 我只从 AzPortal 浏览器读取数据,因为我只会将 MongoDB 驱动程序用于写入目的,并将通过使用其他作业的 DocDB .Net 驱动程序读取数据。那么,有没有办法从MongoDB驱动手动设置real DocDB id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多