Can I use $in to match on multiple fields in an array of objects?

Say I have an array on a document:

things: [
{ a: 1, b: 2, c: 3},
{ a: 1, b: 4, c: 5},
{ a: 2, b: 6, c: 7

How can I use $in to match the document with two criteria, say {a: 1, b: 4} (resulting in a true due to one array object matching). I don’t think an $and with two $in’s would work because it’s testing the two values independently in the array (I want both to be true in the same object).


Yes, it is correct, $in will not work in this case, $elemMatch will help. Please refer to the section Array of Embedded Documents in the link below, it has examples relevant to your case.


The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.


1 Like