Kuan
Kuan

Reputation: 11389

How to search documents which has specified type and contain specific value in mongoDB

I inserted 3 documents into mongodb like this:

db.collection.insert({id:1, value:[1, 2, 3]})
db.collection.insert({id:2, value:[2, 4, 5]})
db.collection.insert({id:3, value:1})

Then I want to:

  1. get the documents whose value's type is an Array and contains 1

  2. get any documents whose value contains or equal 1 or 2 or 5

Could Anyone help me with this?

Upvotes: 0

Views: 40

Answers (1)

Sede
Sede

Reputation: 61225

I want to get the documents whose value's type is an Array and contains 1

Use the $type operator

db.collection.find({ "value": { "$type": 4 }, "value": 1})

I want to get any documents whose value contains or equal 1 or 2 or 5

Use the $in.Quoting the documentation

The $in operator selects the documents where the value of a field equals any value in the specified array.

db.collection.find({ "value": { "$in": [1,2,5] }})

You can do it in one query

db.collection.find({ 
    "$or": [
               { "value": { "$type": 4 }, "value": 1 }, 
               { "value" : { "$in": [1,2,5]}}
           ]
})

Upvotes: 1

Related Questions