Raja Raja - 26 days ago 9
JSON Question

How can I query documents where a values match a parent object and child object?

I'm new to Mongoose and I've been trying for days on how to solve this issue and I'm still having trouble.

My document object is below.

"person" : [
{
"title" : "front-end developer",
"skills" : [
{
"name" : "js",
"project" : "1",
},
{
"name" : "CSS",
"project" : "5",
}
]
},
{
"title" : "software engineer",
"skills" : [
{
"name" : "Java",
"project" : "1",
},
{
"name" : "c++",
"project" : "5",
}
]
}
]


What I would like accomplish is to return all documents that have
person.title
=
software engineer
AND
person.skills.name
=
c++
. The skill
c++
has to belong to the
software engineer
person object. So returning documents when a front-end developer has
c++
is not ideal.

Here's what I've tried doing so far. The query works but it returns documents which meet either one of the conditions and not both.

var query = {
_id: { $nin: [userID] },
$and: [
{person: {
$elemMatch: {
name: {$regex: `^${titleName}$`, $options: "i"}
}
}},
{[`person.skills`]: {
$elemMatch: {
name: {$regex: `^${skillName}$`, $options: "i"}
}
}}
]
};


Any help would be greatly appreciated. Thanks!

Answer Source

You can try below query. Move the and condition inside the $elemMatch

var query = {
  "_id": {
    "$nin": [userID]
  },
  "person": {
    "$elemMatch": {
      "name":{$regex: `^${titleName}$`, $options: "i"},
      "skills.name": {$regex: `^${skillName}$`, $options: "i"}
    }
  }
};