2

I have documents with the following structure:

{field: ["id1", "id3"]},
{field: ["id2", "id1"]}

To query the documents I use

aggregate({$match: {'field' : { $in: ['id1'] }}})

I get the documents with this query but I would like only

{field: ["id2"]},
{field: ["id3"]}

I.e., I want to remove "id1" from the array in the aggregation step only, and not from the actual document (via an update with $pull or something similar).

1 Answer 1

4

Say we have following documents in a collection named collection:

db.collection.insert({field: ["id1", "id3"]})
db.collection.insert({field: ["id2", "id1"]})

Then below aggregation pipeline would do the trick:

db.collection.aggregate([
  {
    $match: {field: "id1"}
  },
  {
    $project: {
      field: {
        $filter: {
          input: "$field",
          as: "item",
          cond: {
            $ne: ["$$item", "id1"]
          }
        }
      }
    }
  }
])

The output from mongo shell is:

{ "field" : [ "id3" ] }
{ "field" : [ "id2" ] }

An alternative way is to $unwind the field and then $group it back:

db.collection.aggregate([
  {
    $match: {field: "id1"}
  },
  {
    $unwind: "$field"
  },
  {
    $group: {
      _id: "$_id",
      field: {
        $push: {
          $cond: {
            if: { $eq: [ "$field", "id1" ] },
            then: "$$REMOVE",
            else: "$field"
          }
        }
      }
    }
  },
  {
    $project: {
      _id: 0
    }
  }
])
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.