I have a collection with: I want to use the $in
operator
Person = {
name: String,
members: [ {id: String, email: String}... {}]
}
I use this so far:
Person.find({members: {"$in": [id1]}})
But I already know the flaw: If the array of members was like Members: [id1, id2, ... id3]
that method would work. But it is an array of objects. So how do I get around it?
So remember, when accessing an array of objects in mongoose, we have to use a dot(.) followed by the field name of the object. Searching inside of an array is very common and it will come in handy so it is great to have it mastered. Thank you for joining us for another Object Rocket knowledge-base tutorial.
You can just simply use count method.
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
$elemMatch
can be used with Arrays of Embedded Documents:
In your case you could try:
Person.find({
members: {
$elemMatch: { id: id1 }
}
});
But since it is a Single Query Condition:
Person.find({
"members.id": id1
});
Would do the trick.
You can use elem match in the following way:
db.collection.find({
arrayfield: {
$elemMatch: {
id: ObjectId("5eaaeedd00101108e1123461")
}
}
})
The same can be done in mongoose in the following ways:
query.elemMatch('arrayfield', { id: ObjectId("5eaaeedd00101108e1123461") })
.
query.where('arrayfield').elemMatch({ id: ObjectId("5eaaeedd00101108e1123461") })
.
query.elemMatch('arrayfield', function (elem) {
elem.where('id').equals(ObjectId("5eaaeedd00101108e1123461"));
})
.
query.where('arrayfield').elemMatch(function (elem) {
elem.where({ id: ObjectId("5eaaeedd00101108e1123461") });
})
I have used this example collection:
[
{
"_id": ObjectId("5eaaeedd00101108e1123451"),
"arrayfield": [
{
id: ObjectId("5eaaeedd00101108e1123461"),
name: "David"
},
{
id: ObjectId("5eaaeedd00101108e1123462"),
name: "Brown"
}
]
},
{
"_id": ObjectId("5eaaeedd00101108e1123452"),
"arrayfield": [
{
id: ObjectId("5eaaeedd00101108e1123471"),
name: "Maple"
},
{
id: ObjectId("5eaaeedd00101108e1123472"),
name: "Green"
}
]
},
{
"_id": ObjectId("5eaaeedd00101108e1123453"),
"arrayfield": [
{
id: ObjectId("5eaaeedd00101108e1123461"),
name: "David"
},
{
id: ObjectId("5eaaeedd00101108e1123482"),
name: "Lacey"
}
]
}
]
Want to try live? Try it on mongo playground with this link https://mongoplayground.net/p/H3fdmp9HkQv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With