avangarde2225
avangarde2225

Reputation: 1

How to write a mongo query that returns fields with the expected results?

For instance I am trying to bring up the organization ids that are tagged to multiple countries in db.

 db.collection.find({"Region":{$in:["CHINA","JAPAN","SOUTH_KOREA"]}}) 

this doesnot give me the results that they have all 3 countries in the same document. Obviously $where does not work which I can query to bring up the fields that have more than 1 country in it.

Trying this for 2 days and need your help.

Thanks in advance.

Upvotes: 0

Views: 159

Answers (4)

avangarde2225
avangarde2225

Reputation: 1

These two queries worked in my case. They are as simple as they look like but somehow I missed them our after many trials I may have miswritten them. Anyways here is the solution to my question:

db.collection.find({region:{$size:3}})
db.collection.find({ "region.2":{$exists:true}})

Upvotes: 0

unltd_J
unltd_J

Reputation: 494

If I'm understanding your question correctly, you are trying to match a document where the Region key is a list conataining all three countries.

  db.collection.find({$and: [
     {Region: {$in: ["CHINA"]}},
     {Region: {$in: ["JAPAN"]}},
     {Region: {$in: ["SOUTH_KOREA"]}}  
])

If so, this should work for you.

Upvotes: 0

Use $all

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

db.collection.find({"Region":{ $all :["CHINA","JAPAN","SOUTH_KOREA"] } }) 

Upvotes: 2

Luis Angel Pena Zuniga
Luis Angel Pena Zuniga

Reputation: 190

i hope this will go acording youre need's:

db.collection.find({
    $and: [
        { Region: {$in: /\bCHINA\b/i} },
        { Region: {$in: /\bJAPAN\b/i} },
        { Region: {$in: /\bSOUTH_KOREA\b/i} }
    ]
})

Upvotes: 0

Related Questions