包含BsonArray的查询集合

时间:2017-10-01 18:32:00

标签: arrays mongodb mongodb-query

抱歉,第一次尝试mongo。

鉴于以下数据......

db.masterList.findOne()
{
        "_id" : ObjectId("59d128805b19310ac8ab3fc2"),
        "MasterDefinition" : {
                "Location" : [
                        "Whole House",
                        "Master Bedroom",
                        "Hallway 2"
                ],
                "DeviceType" : [
                        "Receptacle",
                        "GFI",
                        "LED dimmer"
                ],
                "Style" : [
                        "Decora",
                        "Standard"
                ],
                "Color" : [
                        "White",
                        "Light Almond"
                ]
        }
}

如何检索Color数组的内容?我期待像

这样的东西
["White","Light Almond"]

如何列出直接从属于MasterDefintion的4个数组?我希望看到

["Location","DeviceType","Style","Color"]

由于

2 个答案:

答案 0 :(得分:0)

对于第一部分,您只需执行

即可
collection.aggregate({
    $project: {
        "_id": 0, // exclude the "_id" field from the result
        "result": "$MasterDefinition.Color"
    }
})

第二部分需要一点魔力(文档可以在这里找到:aggregation framework$project$objectToArray):

collection.aggregate({
    $project: {
        "temp": {
            $objectToArray: "$MasterDefinition" // transform the "MasterDefinition" subdocument into an array
        }
    }
}, {
    $project:{
        "_id": 0, // do not include the "_id" field in the result - this is an optional step
        "result": "$temp.k" // only get the keys (as in "k" fiels) from the array
    }
})

答案 1 :(得分:0)

  

如何检索Color数组的内容?我期待像“白色”,“浅杏仁”这样的东西

var list = db.Items.Where(c => c.id == 0).GroupBy(c => c.id);}

上面的命令将返回:

// the first argument here is a filter, the second argument is a projection
// since you specified no filter I have only included a projection
// this projection tells MongoDB to return the Color subdocument 
// from within the MasterDefinition sub document
db.getCollection('masterList').find({}, {'MasterDefinition.Color': 1})
  

如何列出直接从属于MasterDefintion的4个数组?我希望看到[“位置”,“设备类型”,“风格”,“颜色”]

这有点棘手,因为“Location”,“DeviceType”,“Style”,“Color”不是数组中的元素,而是{ "_id" : ObjectId("59d128805b19310ac8ab3fc2"), "MasterDefinition" : { "Color" : [ "White", "Light Almond" ] } } 子文档中的属性名称。您可以使用$objectToArray aggregation operator将这些属性名称转换为数组,但生成的文档看起来并不像您希望的那样。这是一个例子......

MasterDefinition

...产生此输出:

db.getCollection('masterList').aggregate([

    // creates an array named "categories" from the attributes of the MasterDefinition sub document
    { $project: { categories: { $objectToArray: "$MasterDefinition" } } }, 

    // projects on the keys of the "categories" array
    {$project: {'categories.k': 1}}

])