Valerio
Valerio

Reputation: 3615

MongoDB filter with composite object

Imagine having a MongoDB collection with this "schema":

mycollection: {
    name: String
    treatments: [{
        type: ObjectId,
        colors: ObjectId[]
    }]
}

and have a couple of record like this

{
    name: "Foo",
    treatments:[
        { type: ObjectId('123456'), colors: [ObjectId('654321')] }
   ]
},
{
    name: "Bar",
    treatments:[
        { type: ObjectId('123456'), colors: [ObjectId('789012')] }
   ]
}

If I try to filter those record using:

{ "treatments.type": ObjectId('123456'), "treatments.colors": { $in: [ObjectId('654321')] } }

I expect that returns only the record with name "Foo", but instead it returns both records, treating the filter like an OR. Even

{ $and: [{ "treatments.type": ObjectId('123456') }, { "treatments.colors": { $in: [ObjectId('654321')] } ] }

returns the same.

Any help or clarification would be greatly appreciated ❤️

Upvotes: 0

Views: 332

Answers (1)

Anku Singh
Anku Singh

Reputation: 954

In this case you need to use elemMatch in mongodb this will find the element from array which has both the condition true

{ treatments: { $elemMatch: { type: ObjectId('123456'), colors: { $in: [ObjectId('654321')] } } } }

otherwise it is default behaviour in mongodb that when specifying conditions on more than one field nested in an array of documents, you can specify the query such that either a single document meets these condition or any combination of documents (including a single document) in the array meets the conditions. check this link for further explanation https://docs.mongodb.com/manual/tutorial/query-array-of-documents/

Upvotes: 1

Related Questions