c# - 带有 MongoDB .NET 驱动程序的 Azure DocumentDB : how to set id manually?

标签 c# .net mongodb azure azure-cosmosdb

我想更新插入 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"

DocumentDB .NET 库允许我自己设置 id(如果我只输入属性名称 id)。如何使用 MongoDB .NET 驱动程序做到这一点?

最佳答案

在 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

关于c# - 带有 MongoDB .NET 驱动程序的 Azure DocumentDB : how to set id manually?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43803451/

相关文章:

c# - LINQ:单个谓词中的多个 LIKE 子句

c# - C#中如何枚举COM对象的成员?

.net - 将控制台颜色转换为颜色?

python - 使用 HTTP GET 请求访问 nodejs 服务器上的 MongoDB 数据库

mongodb - 无法连接到 Dockerized MongoDb 服务器 - 绑定(bind) ip - 没有机会授权

c# - Chrome 驱动程序在 FindElement 调用中抛出脚本结果错误

c# - 基于角色的身份验证

c# - Visual Studio 代码分析规则 - "Do not expose generic lists"

.net - 为什么 byte[] 的最大大小为 2 GB - 57 B?

javascript - Mongoose 查询 - 删除以子文档值为条件的文档