如何使用对象数组中的字段查询mongodb

时间:2015-08-06 09:10:31

标签: mongodb mongoose

我有一个这样的db对象:

{
   "_id": ObjectID("55c247f94b0c25e5d90d0f39"),
   "districts": [
    {
        "district": "Bangalore Urban",
        "stateID": 2,
        "districtID": 1
    },
    {
        "district": "Tumkur",
        "stateID": 2,
        "districtID": 2
    }
]
}

我和我有stateID,我应该编写什么mongoose查询来获取数组districts中具有stateID 2的所有对象

请帮忙!

1 个答案:

答案 0 :(得分:3)

您需要aggregate查询。您的Mongo查询将如下所示:

db.collection.aggregate([{
    $unwind: 'districts'
}, {
    $match: {
        'stateID': 2
    }
}, {
    $group: {
        _id: null,
        'districts': {
        $push: '$districts'
        }
    }
}]);

$unwind从数组中的每个项目创建一条记录。

$match是您查找州ID项目的查询

$group将您的所有结果分组到自定义键