0

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.

3
  • if you use update, that second param is not your condition Commented Nov 23, 2017 at 4:05
  • OP: You have two distinct things going on here: update and query. Perhaps you can separate them and describe your desired output? Commented Nov 23, 2017 at 4:13
  • check this how to change order of array with mongodb Commented Nov 23, 2017 at 4:25

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

While this will work, if the letters to match increase in count, this solution will become too complex.
0
    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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.