MongoDb c#驱动投影返回名称和值对

本文关键字:返回 投影 MongoDb | 更新日期: 2023-09-27 18:02:47

原始数据是这样的

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

我怎么能实现像db.getCollection('products').find({},{entityId:1})与c#驱动程序?

MongoDb c#驱动投影返回名称和值对

这是正常行为。查找只返回指定字段和_id字段vs只返回指定字段在官方文档。

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