简体   繁体   中英

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. Because the same letters are already present in the array.

i will try with $all operator but it doesn't work

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"] .

    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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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