Till
Till

Reputation: 38

MongoDB query for documents that contain at least one of the values specified in an array

I have a collection in MongoDB that is structured like this:

[
  {
    "_id": ObjectId("51bf000a3d489f2df59aa4c6"),
    "courses": ["course1", "course2"]
  }, {
    "_id": ObjectId("52cc789a4df828450c16e52c"),
    "courses": ["course3", "course4"]
  }
]

I’d like to be able to query for both documents with an array like ["course1", "course3"] where "course1" matches the first and "course3" matches the second document.

Is this possible without a complex query like this?

{
  "$or": [
    { "courses": "course1" },
    { "courses": "course3" }
  ]
}

Sorry for my poor English!

Upvotes: 0

Views: 2366

Answers (2)

Ram Dwivedi
Ram Dwivedi

Reputation: 470

If you want to further work on your resultset, you can also use aggregates and tweak your result as you wish.

db.courses.aggregate([
            {$unwind:"$courses"},
            {$match:{$or:[{courses:"course1"},{courses:"course3"}]}},
            {$project:{_id:0, courses:1}}
    ]);

or use $in operator as below:

db.courses.aggregate([
        {$unwind:"$courses"},
        {$match:{courses:{$in:["course1","course3"]}}},
        {$project:{_id:0, courses:1}}
        ])

Upvotes: 0

Ivan.Srb
Ivan.Srb

Reputation: 1851

Following query is equal to your:
db.coll.find({ courses: { $in: ["course1", "course3"] } })

Upvotes: 2

Related Questions