mongoDB : 在列表中以任意顺序查找列表

mongoDB : find list in list with any order

我正在尝试在 mongoDB 中执行查找请求,条件是: "if element contains a list that contains exactly theses elements"。 举个例子更有意义:

{
"categories" : [ 
        [ 
            "dogs", 
            "cats"
        ], 
        [ 
            "dogs", 
            "octopus"
        ]
    ]
}

我想查找类别仅包含 "dogs" 和 "octopus" 的元素。

find({ 'categories' : ['dogs','octopus']}) 找到元素

find({ 'categories' : ['octopus','dogs']}) 找不到,这就是我的问题所在,因为我不关心列表中的顺序

输出将是类别仅包含 "dogs" 和 "octopus"

的所有元素

我不确定是否可行,但如果不是,我看到的两个解决方案是按字母顺序存储它们(很好,但如果我之后需要顺序怎么办?)或 store/search 所有可能的订单(非常难看)

您可以使用aggregation pipelines

 db.collection.aggregate([
    { "$unwind": "$categories" }, 
    { "$match": { "categories" : { "$all" : [ "dogs", "octopus" ]}}}
])

这将为您提供以下文档

{ 
    "_id" : ObjectId("54c6685e7cdaa3f3e4dd8def"),
    "categories" : [ "dogs", "octopus" ] 
}