24

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?

0

3 Answers 3

42

$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.

Sign up to request clarification or add additional context in comments.

1 Comment

best answer imo.
4

You can use members.id as field in your query to match your subdocument ids :

Person.find({ "members.id": { "$in": ["id1"] } })

Comments

4

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

1 Comment

i wanna match multiple ids like 5eaaeedd00101108e1123461, 5eaaeedd00101108e1123482 to find devid and lacey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.