簡體   English   中英

MongoDb C# 驅動程序投影返回名稱和值對

[英]MongoDb C# driver projection returns name and value pair

原始數據看起來像這樣

{
"_id" : ObjectId("57b532aefc19a526b4cf7118"),
"_t" : [ 
    "Product", 
    "ShoppingProduct"
],
"name" : "nike jug",
"createdByUser" : "",
"updatedAt" : ISODate("2016-08-18T03:59:42.012Z"),
"url" : "https://localhost:44305/v1/product/1",
"description" : "a jug from nike",
"schema" : "ShoppingProduct",
"sku" : "nikejug001",
"price" : "15",
"weight" : "100",
"brand" : null,
"manufacturerId" : ObjectId("000000000000000000000000"),
"entityId" : 1,
"visibility" : 4,
"status" : 1,
"taxClassId" : 2,
"shortDescription" : "nike jug is good"
}

我做了這個

var result = _col.Find("{}").Project("{entityId:1}").ToList();

我希望返回數據是這樣的

{
"_id" : ObjectId("57b532aefc19a526b4cf7118"),
"entityId" : 1
}

但我得到的是這樣的:

{
  "name": "_id",
  "value": "57b532aefc19a526b4cf7118"
},
{
  "name": "entityId",
  "value": 1
}

我怎樣才能用 C# 驅動程序實現像db.getCollection('products').find({},{entityId:1})

這是正常行為。 Lookup Return the Specified Fields and the _id Field Only vs Return Specified Fields Only in the official docs。

var empty = Builders<BsonDocument>.Filter.Empty;
var docs = _col.Find(empty).Project("{_id:0, entityId:1}").ToList();
foreach (var doc in docs)
{
  if (doc.AsBsonDocument.ElementCount != 1)
    throw new Exception("Should have only entityId fields");
}
docs = _col.Find(empty).Project("{entityId:1}").ToList();
foreach (var doc in docs)
{
  if (doc.AsBsonDocument.ElementCount != 2)
    throw new Exception("Should have _id and entityId fields");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM