0

I need to query entries in an array, the document looks like this:

{
   "_id":"5d7b4ef6f691b71b5097e9cb",
   "name":"1568362230828",
   "commands":[
      {
         "_id":"5d7b4ef6f691b71b5097e9d1",
         "name":"Command - 0"
      },
      {
         "_id":"5d7b4ef6f691b71b5097e9d0",
         "name":"Command - 1"
      },
      {
         "_id":"5d7b4ef6f691b71b5097e9cf",
         "name":"Command - 2"
      },
      {
         "_id":"5d7b4ef6f691b71b5097e9ce",
         "name":"Command - 3"
      },
      {
         "_id":"5d7b4ef6f691b71b5097e9cd",
         "name":"Command - 4"
      },
      {
         "_id":"5d7b4ef6f691b71b5097e9cc",
         "name":"Command - 5"
      }
   ],
   "__v":0
}

now i want to get all commands by there id:

model.find({
commands: {
_id: ["5d7b4ef6f691b71b5097e9cf", "5d7b4ef6f691b71b5097e9cf"] }})

Pseudo query, this does not work!

How must my query looks like ?!

const schema = new mongoose.Schema({
    name: String,
    commands: [{
        name: String
    }]
});

const model = mongoose.model('Endpoints', schema);
5
  • model.find({"commands._id": {$in:["5d7b4ef6f691b71b5097e9cf", "5d7b4ef6f691b71b5097e9cf"] }}) will return you all models that have at least one command with given id. Commented Sep 13, 2019 at 10:18
  • i need only the commands (as array) with the given ids Commented Sep 13, 2019 at 10:24
  • Then you need to use aggregation, extract commands on application level, or query commands collection. How your "model" and "command" schemas are defined in mongoose? Commented Sep 13, 2019 at 10:29
  • added the schema, i hoped i can only filter for the given/needed commands Commented Sep 13, 2019 at 10:52
  • Cool, so commands are embedded. Use aggregation Commented Sep 13, 2019 at 11:13

1 Answer 1

1

If you want to un-filter comments in comments only document then use this query

Endpoints.find({
   commands: {
     $elemMatch: {
       _id: { $in: ["5d7b4ef6f691b71b5097e9cf", "5d7b4ef6f691b71b5097e9cf"] }
     }
   }
});

If you want to filter comments in comments

Endpoints.aggregate([
   {
      $project: {
         items: {
            $filter: {
               input: "$commands",
               as: "item",
               cond: { 
                   $in: [ 
                      "$$item._id",
                      ["5d7b4ef6f691b71b5097e9cf", "5d7b4ef6f691b71b5097e9cf"]
                   ]
              }
            }
         }
      }
   }
])

or without aggregation

Endpoints.find(
     { commands: 
       {$elemMatch: {"_id": { $in: ["5d7b4ef6f691b71b5097e9d1"]}}}
     }, 
     { 'commands.$': 1 }
 )
Sign up to request clarification or add additional context in comments.

Comments

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.