简体   繁体   English

在mongodb中搜索嵌套数组元素

[英]Searching nested array elements in mongodb

i have collection called 'test' in that there is a document like: 我有一个名为“测试”的集合,其中有一个像这样的文档:

{
"_id" : 1
"letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "E", "B", "F" ]
    ]
}

if i search like this: 如果我这样搜索:

db.getCollection('test').find({"_id" : 1}, {"letters": ["A", "B"] })

then it will fetch the record. 然后它将获取记录。

{
"_id" : 1
"letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "E", "B", "F" ]
    ]
}

if i search like this: 如果我这样搜索:

db.getCollection('test').find({"_id" : 1}, {"letters": ["B", "A"] })

it doesn't fetch the record 它不会获取记录

my requirment is if im give like this also (["B", "A"]), it have to fetch the document. 我的要求是,如果im也这样给出([“ B”,“ A”]),则必须获取文档。 Because the same letters are already present in the array. 因为数组中已经存在相同的字母。

i will try with $all operator but it doesn't work 我将尝试使用$ all运算符,但它不起作用

db.getCollection('test').find({"_id" : 1}, {"letters": {$all: ["B", "A"]} })

now also it will not fetch the record 现在也不会获取记录

could anyone can please give the solution. 谁能给我解决方案。

You can do something like this : 您可以执行以下操作:

 db.test.find(
       {
        "$and":[
         {"_id" : ObjectId("5a16674b4828c9f51d3b3a18")},
         {"$or":[{"letters": ["A", "B"] },{"letters": ["B", "A"] }]}
               ]
       }
      )

Now it will search the document who has ["A","B"] OR ["B","A"] . 现在它将搜索具有["A","B"] OR ["B","A"]的文档。

    db.getCollection('test').find(
        {
            "_id" : 1,
            'letters':{
                $elemMatch:{
                    $elemMatch:{
                        $in:['B','A']
                    }
                }
            }
        }
    )

This query will find all the documents which has array elements you specify in last $in close, example, It will find same document if you specify only $in:['C'] or $in:['B','A'] 该查询将找到所有具有您在最后$ in关闭中指定的数组元素的文档,例如,如果仅指定$ in:['C']或$ in:['B','A',它将找到相同的文档。 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM