在mongodb中检索并更新子文档

时间:2018-04-20 12:55:16

标签: c# .net mongodb

我想从文档中获取其子文档。我有这样的结构:

{"_id" : "5ad6729179b9c00808ea9cdf",
"CreatedDate" : ISODate("2018-04-17T22:17:53.696Z"),
"UpdatedDate" : ISODate("2018-04-17T22:17:53.698Z"),
"Label" : "2018-Q1",  
"Sections" : [ 
    {
        "_id" : "5ad6729179b9c00808ea9ce0",
        "Label" : "TWN-25",
        "Groups" : [ 
            {
                "_id" : "5ad6729179b9c00808ea9ce1",
                "Label" : "Group1"                    
            }, 
            {
                "_id" : "5ad6729179b9c00808ea9ce2",
                "Label" : "Group 2"                    
            }, 
            {
                "_id" : "5ad6729179b9c00808ea9ce3",
                "Label" : "Group3"             
            }
        ]
    }, 
    {
        "_id" : "5ad6729179b9c00808ea9ce4",
        "Label" : "TWN-26",
        "Groups" : [ 
            {
                "_id" : "5ad6729179b9c00808ea9ce5",
                "Label" : "Group4"    
            }
        ]
    }
]}

我接下来找到查询

        var builder = Builders<BsonDocument>.Filter;
        var filter = builder.Eq("_id", questionnaireId) & builder.Eq($"Sections._id", sectionId) &
            builder.Eq("Sections.Groups._id", groupId);

但我想从文档中只获取Group子文档。为此,我必须建立投影。这是我的预测:

var project = Builders<BsonDocument>.Projection.Include("Sections.Groups.$");

我称之为

var result = Collection.Find(filter).Project(project).FirstOrDefault();

但我仍然得到所有文件,而不仅仅是子文件Group。我做错了什么?

1 个答案:

答案 0 :(得分:1)

在理想世界中,我建议您使用以下查询:

"access to healthcare

"

但是,不幸的是,您将获得以下异常:

db.getCollection('Test').find(
{
        "Sections.Groups._id":"5ad6729179b9c00808ea9ce3"
}, 
{ 
        "Sections.Groups": 
        {
                "$elemMatch" : {"_id":"5ad6729179b9c00808ea9ce3" } 
        }
} )

您基本上有两个选择:

使用聚合框架

Cannot use $elemMatch projection on a nested field

使用以下查询

db.Test.aggregate( [
   {$match: { "Sections.Groups._id":"5ad6729179b9c00808ea9ce3" } },   
   {$unwind: "$Sections"},
   {$replaceRoot: { newRoot: "$Sections"} },
   {$unwind: "$Groups"},
   {$replaceRoot: { newRoot: "$Groups"} },
   {$match: { "_id":"5ad6729179b9c00808ea9ce3" }}
] )

我会选择第一个选项,虽然效率不高