【问题标题】:How to find all documents with all specified array values in it in mongoDB?如何在mongoDB中查找所有指定数组值的文档?
【发布时间】:2017-06-05 16:28:50
【问题描述】:

这是我的收藏

{
    "_id" : ..., 
    "name" : "sport", 
}
{
    "_id" : ..., 
    "name" : "art", 
}
{
    "_id" : ..., 
    "name" : "cars", 
}

这是我得到的数组["cars","sport"] 我只是想确保我的收藏中有cars sport,如果没有(或只有一个不存在)我想收到什么都没有强>。 我正在寻找类似 $inand 模式的数组友好型查询。

【问题讨论】:

    标签: arrays mongodb database


    【解决方案1】:

    这就是你在看的……??

    db.colllection.find( {$and: [ {"name": {$in: ["cars"]}}, {"name": {$in: ["sports"]}} ] })

    【讨论】:

    • 不,这是答案,谢谢。如果它找到任何一个,或者两者都找到,这只会起作用。
    【解决方案2】:

    以下查询应该可以帮助您实现这一目标

    //change test with your collection name
    db.getCollection('test').aggregate(
        {
            $group: {
                _id: "collectionOfNames",
                "names": {$addToSet: "$name"}
            }
        },
        {
            $match: {"names": {$all: ["cars", "sport"]}}
    
        }
    )
    

    我们使用 $group 在所有文档中创建属性 name 的数组“名称”。 然后使用 $match 和 $all 我们检查以确保数组“names”包含我们查询数组中的所有元素。

    这是你要找的吗?

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2020-05-17
      • 2015-09-02
      • 2012-01-08
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多