c# - MongoDb C# 驱动程序投影返回名称和值对

标签 c# mongodb

原始数据是这样的

{
"_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}) 的功能?

最佳答案

这是正常行为。查询Return the Specified Fields and the _id Field Only对比Return Specified Fields Only在官方文档中。

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

关于c# - MongoDb C# 驱动程序投影返回名称和值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39010417/

相关文章:

ruby-on-rails - 将 Activerecord 数据库迁移到 Mongoid

node.js - 如何更新多个文档?

.net - 为什么我的现金抽屉没有出现在 pos for .net 的设备列表中?

c# - 使用 CultureInfo 格式化 C# 图表轴

node.js - 对从 populate 返回的文档使用用户定义的模式方法

arrays - Mongodb:对分组后的子文档中的值进行求和,然后查找,然后展开

node.js - 如何在 mongoose hook 中保存 userId?

c# - XMLSerializer 在反序列化派生类型时警告未知节点/属性

c# - 将 XML 字符串添加到 XElement

c# - 使用 LINQ 获取平均值