从mongoDB文档中检索特定元素的数组

时间:2015-09-09 18:02:17

标签: mongodb

下面是一个mongoDB文档,其中包含一个items字段,它是一个文档数组(类似对象类型)

{
    "_id" : ObjectId("55ef38cc426e994a8590fce8"),
    "items" : [ 
        {
            "drId" : "55ef34d3426eee33f626efc5",
            "duration" : {
                "value" : "1",
                "durationUnit" : {
                    "_id" : null,
                    "unit" : "Week",
                    "dId" : "55edf013426eb4845f2e0f9b",
                    "lId" : "55edf013426eb4845f2e0fa1",
                    "hId" : "55edf013426eb4845f2e0fa0"
                }
            },
            "dos" : "1-1-1",
            "direction" : [ 
                {
                    "_id" : null,
                    "direction" : "Test Direction",
                    "dId" : "55edf013426eb4845f2e0f9b",
                    "lId" : "55edf013426eb4845f2e0fa1",
                    "hId" : "55edf013426eb4845f2e0fa0"
                }
            ],
            "instructions" : "Test Instructions"
        },
    {
            "drId" : "55ef34d3426eee33f626efc6",
            "duration" : {
                "value" : "1",
                "durationUnit" : {
                    "_id" : null,
                    "unit" : "Week",
                    "dId" : "55edf013426eb4845f2e0f9b",
                    "lId" : "55edf013426eb4845f2e0fa1",
                    "hId" : "55edf013426eb4845f2e0fa0"
                }
            },
            "dos" : "1-1-1",
            "direction" : [ 
                {
                    "_id" : null,
                    "direction" : "Test Direction",
                    "dId" : "55edf013426eb4845f2e0f9b",
                    "lId" : "55edf013426eb4845f2e0fa1",
                    "hId" : "55edf013426eb4845f2e0fa0"
                }
            ],
            "instructions" : "Test Instructions"
        }
    ]
}

我想检索一个只有drId的数组(如果是上面的文档)

例如。结果应该是

["55ef34d3426eee33f626efc5", "55ef34d3426eee33f626efc6"]

这可以在mongoDB中实现吗?

2 个答案:

答案 0 :(得分:3)

您可以使用distinct找到以下内容:

db.collection.distinct("items.drId")

或者使用$map汇总的帮助如下:

db.collection.aggregate({"$project":{"drId":{"$map":{"input":"$items","as":"el","in":"$$el.drId"}},"_id":0}})

答案 1 :(得分:0)

使用以下聚合管道:

db.test.aggregate([
    {
        "$unwind": "$items"
    },
    {
        "$group": {
            "_id": null,
            "drIds": {
                "$push": "$items.drId"
            }
        }
    },
    {
        "$project": {
            "_id": 0, "drIds": 1
        }
    }
])

<强>输出

/* 0 */
{
    "result" : [ 
        {
            "drIds" : [ 
                "55ef34d3426eee33f626efc5", 
                "55ef34d3426eee33f626efc6"
            ]
        }
    ],
    "ok" : 1
}