如何在mongoDB中投影过滤后的数组元素

时间:2016-12-29 17:45:40

标签: mongodb

以下MongoDB文档包含workflow元素的数组。根文档具有_id,并且每个工作流都具有唯一的_id

{
    "_id" : ObjectId("54aedb94e6c12b1c0e83385f"), //root id
    "name" : "somename",
    "workflows" : [ 
        {
            "name" : "Workflow1",            
            "_id" : ObjectId("54aedb94e6c12b1c0e83394c"),
            "taskGroups" : [ 
                {
                    "processingPhase" : "PHASE1",                    
                    "_id" : ObjectId("555b62f89a2582000e360cff")                    
                }, 
                {
                    "processingPhase" : "PHASE2",                    
                    "_id" : ObjectId("555b62f89a2582000e360cc2"),
                }, 
                {
                    "processingPhase" : "PHASE3",                    
                    "_id" : ObjectId("555b62f89a2582000e360c80"),
                }
            ]
        },
        {
            "name" : "Workflow2",            
            "_id" : ObjectId("54aedb94e6c12b1c0e83389e"),
            "taskGroups" : [ 
                {
                    "processingPhase" : "PHASE1",                    
                    "_id" : ObjectId("555b63169a2582000e360d8e")           
                }, 
                {
                    "processingPhase" : "PHASE2",                    
                    "_id" : ObjectId("555b63169a2582000e360d51")
                }, 
                {
                    "processingPhase" : "PHASE3",                    
                    "_id" : ObjectId("555b63169a2582000e360d0f")
                }
            ]
        }, 
    ],
    "__v" : 54
}

鉴于根文档的_id和工作流的_id,我想选择单个工作流并投影其taskGroups子项。

public void SelectTaskGroups(string rootid,string workflowid)
{
    var projection = Builders<BsonDocument>.Projection
       .Include("workflows.taskGroups");
    var filterBuilder = Builders<BsonDocument>.Filter;
    var filter = filterBuilder.Eq("_id", ObjectId.Parse(rootid)) &
        filterBuilder.Eq("workflows._id", ObjectId.Parse(workflowid));
    var tg = await clientCollection
        .Find(filter)
        .Project(projection)
        .SingleOrDefaultAsync()
        .ConfigureAwait(false);
}

但是上面的C#代码会投影整个文档。我只想预测已过滤的taskGroups

workgroup元素

0 个答案:

没有答案