Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
不同类别集合的MongoDB查询_Mongodb_Mongodb Query - Fatal编程技术网

不同类别集合的MongoDB查询

不同类别集合的MongoDB查询,mongodb,mongodb-query,Mongodb,Mongodb Query,我的Mongo数据库有一个字段,其中包含一个字符串数组,如下所示: db.band.insertMany([ { name: "Alice", instrument: ["guitar", "voice"] }, { name: "Bob", instrument: ["bass"] }, { name: "Eve", instrument: ["drums", "voice"] } ]); 我想查询数据库,找到乐队成员可以演奏的一组不同乐器(在本例中:[“吉他”、“声音”、

我的Mongo数据库有一个字段,其中包含一个字符串数组,如下所示:

db.band.insertMany([
   { name: "Alice", instrument: ["guitar", "voice"] },
   { name: "Bob", instrument: ["bass"] },
   { name: "Eve", instrument: ["drums", "voice"] }
]);
我想查询数据库,找到乐队成员可以演奏的一组不同乐器(在本例中:
[“吉他”、“声音”、“贝司”、“鼓”]

可以用一个简单的查询来实现这一点吗?我找不到与此相关的任何内容。

您可以使用获取每个仪器的文档,然后使用获取所有文档的唯一值:

db.band.aggregate([
    {
        $unwind: "$instrument"
    },
    {
        $group: {
            _id: null,
            instruments: { $addToSet: "$instrument" }
        }
    }
])
产出:

{
    "_id": null,
    "instruments": [
        "drums",
        "bass",
        "voice",
        "guitar"
    ]
}