繁体   English   中英

在mongodb中检索和更新子文档

[英]Retrieve and update sub document in 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子文档。 为此,我必须构建Projection。 这是我的预测:

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

我这样称呼它

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

但是我仍在获取所有文件,而不仅仅是子文件Group 我做错了什么?

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

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

使用以下查询

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

我会选择第一个选项,尽管它不是很有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM