Mongoose, check if value exists in an array of objects
$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 linkhttps://mongoplayground.net/p/H3fdmp9HkQv
You can use members.id
as field in your query to match your subdocument id
s :
Person.find({ "members.id": { "$in": ["id1"] } })