1

I have a aggregation pipeline that currently returns example list:

[
    {
        "_id": "5b527a2bfadb811c4869e802",
        "tasks": [
            {
                "done": false,
                "_id": "5b53494987eea4171d199dd3"
            },
            {
                "done": false,
                "_id": "5b53495087eea4171d199dd4"
            },
            {
                "done": false,
                "_id": "5b53495987eea4171d199dd5"
            }
        ],
        "doneTasks_ids": [
            "5b53494987eea4171d199dd3",
            "5b53495087eea4171d199dd4"
        ]
    },
    {
        "_id": "5b527a2ffadb811c4869e803",
        "tasks": [
            {
                "done": false,
                "_id": "5b53496b87eea4171d199dd6"
            },
            {
                "done": false,
                "_id": "5b53497287eea4171d199dd7"
            }
        ],
        "doneTasks_ids": [
            "5b53497287eea4171d199dd7"
        ]
    }
]

Now I want to set done flag for each tasks.done element to true only when the tasks._id is present in doneTasks_ids. I'm pretty sure I should use $map and $in operators, however I'm currently not able to achieve the effect I need. Any help is greatly appreciated

1 Answer 1

1

You can try below aggregation

Basically you need to loop over each task through $map aggregation and check for the _id in doneTasks_ids array with $in aggregation

db.collection.aggregate([
  { "$addFields": {
    "tasks": {
      "$map": {
        "input": "$tasks",
        "as": "task",
        "in": {
          "_id": "$$task._id",
          "done": {
            "$in": ["$$task._id", "$doneTasks_ids"]
          }
        }
      }
    }
  }}
])

Output

[
  {
    "_id": "5b527a2bfadb811c4869e802",
    "doneTasks_ids": [
      "5b53494987eea4171d199dd3",
      "5b53495087eea4171d199dd4"
    ],
    "tasks": [
      {
        "_id": "5b53494987eea4171d199dd3",
        "done": true
      },
      {
        "_id": "5b53495087eea4171d199dd4",
        "done": true
      },
      {
        "_id": "5b53495987eea4171d199dd5",
        "done": false
      }
    ]
  },
  {
    "_id": "5b527a2ffadb811c4869e803",
    "doneTasks_ids": [
      "5b53497287eea4171d199dd7"
    ],
    "tasks": [
      {
        "_id": "5b53496b87eea4171d199dd6",
        "done": false
      },
      {
        "_id": "5b53497287eea4171d199dd7",
        "done": true
      }
    ]
  }
]

You can try it here

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.