c# - 从子文档数组中获取部分模型数组(MongoDB C# 驱动程序)

标签 c# mongodb mongodb-.net-driver

我正在尝试接收仅使用 MongoDB C# 驱动程序填充子字段的新数组。例如我有以下文档:

{
    "_id" : "fca739d0-cddd-4762-b680-597d2996404b",
    "Status" : 1,
    "AccountId" : "1112",
    "Timestamp" : ISODate("2016-04-27T13:46:01.888Z"),
    "CartItems" : [ 
        {
            "ProductId" : "222",
            "Price" : 100,
            "ShippingPrice" : 20,
            "Quantity" : 3
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 2
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 1
        }, 
        {
            "ProductId" : "504",
            "Price" : 200,
            "ShippingPrice" : 20,
            "Quantity" : 1
        }
    ]
}

我正在尝试接收包含新的 CartItems 数组且仅包含 ProductId 的文档,因此响应如下所示:

{
    "_id" : null,
    "Status" : 0,
    "AccountId" : null,
    "Timestamp" : ISODate("2016-04-27T13:46:01.888Z"), (**default)
    "CartItems" : [ 
        {
            "ProductId" : "222",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }, 
        {
            "ProductId" : "504",
            "Price" : 0,
            "ShippingPrice" : 0,
            "Quantity" : 0
        }
    ]
}

我尝试(使用 C#)的投影是

ProjectionDefinition<Cart, Cart> projectionDefinition = Builders<Cart>.Projection.Include(doc => doc.CartItems[0].ProductId)                                                                                      .Exclude(doc => doc.Id);

但结果是具有所有默认值(包括 ProductId)的 CartItems 数组。我做错了什么?

最佳答案

根据文档:

Use the dot notation to refer to the embedded field

https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/#return-specific-fields-in-embedded-documents

所以你的投影应该是这样的:

Builders<Cart>.Projection
.Include("CartItems.ProductId")
.Exclude(doc => doc.Id);

关于c# - 从子文档数组中获取部分模型数组(MongoDB C# 驱动程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968069/

相关文章:

javascript - Node.js - 显示来自 MongoDB 的图像

mongodb - 重命名位于数组中的复杂类型的字段

c# - DeleteManyAsync 会在删除文档时锁定 MongoDB 集合吗?

c# - Keyset(Seek) 分页和 MongoDb 驱动程序 C#

c# - 将 UTF-8 转换为简体中文 (GB2312)

c# - 无法杀死的进程

c# - 按钮有时会重定向到 "This page cannot be displayed"

Mongodb_Hadoop MapReduce

c# - 实体类型 'Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>' 需要定义键

javascript - 如何在mongodb中聚合显示其他字段