Timmy Mucks
Timmy Mucks

Reputation: 247

MongoDB - Get only those documents that matched with an array of ids

I am facing a problem with the Mongoose schema collection which has a nested array of objects. The collection name is Sprint which contains tasks as a sub-document i.e an array of objects.

The schema is something like this.

// document 1
{
    _id: ObjectId("6138e5866b19971ba8a60851"),
    tasks: [
        {
            _id: ObjectId("6138e5ad6b19971ba8a60852"),
            taskName: "Hello"
        },
        {
            _id: ObjectId("6138e5ad6b19971ba8a543252"),
            taskName: "Hello 2"
        }
    ]
},
// document 2
{
    _id: ObjectId("6138e5866b19971ba8a76851"),
    tasks: [
        {
            _id: ObjectId("6138e5ad6f19971ba8a60852"),
            taskName: "World"
        },
        {
            _id: ObjectId("6138e5ad6sd19971ba8a543252"),
            taskName: "World 2"
        }
    ]
}

My goal was to get only those tasks objects in an array that matched with the given ids.

My taskIds array is something like this.

const taskIds = ["6138e5ad6b19971ba8a60852", "6138e5ad6b19971b568a60852"];

and I am using the $in comparison operator to get these tasks.

const query =  {"tasks._id": {$in: taskIds}};
const tasks = await Sprint.find(query);
console.log(tasks);

But the data which I am getting is an array of whole documents with its tasks in an array of objects. I still don't know how to get only those tasks in an array that matched with the ids.

Upvotes: 0

Views: 1151

Answers (1)

J.F.
J.F.

Reputation: 15235

If I've understood correctly you can use this query:

  • $unwind to deconstruct the array.
  • $match by your criteria.
  • $group using null as _id because yo want to get all tasks values.
  • And (optional) $project to not show the _id
db.collection.aggregate([
  {
    "$unwind": "$tasks"
  },
  {
    "$match": {
      "tasks._id": {
        "$in": [
          "6138e5ad6b19971ba8a60852",
          "6138e5ad6b19971b568a60852"
        ]
      }
    }
  },
  {
    "$group": {
      "_id": null,
      "tasks": {
        "$push": "$tasks"
      }
    }
  },
  {
    "$project": {
      "_id": 0
    }
  }
])

Example here

Also, to explain why using you query mongo shows the entire object is because with that query you are telling mongo "five me the documents where the _id field in tasks array is in this array". And mongo get the entire object where the criteria is done.

Upvotes: 2

Related Questions