user12983086
user12983086

Reputation:

Drop unmatched values in a aggregation

have a collection like this

[
  {
    _id: ObjectId("5ab9cbe531c2ab715d42129a"),
    p_id: ObjectId("507f191e810c19729de860ea"),
    name: "elmaro",
    mobile: 112466,
    area: "texas",
    mapped: [
      {
        _id: ObjectId("5e13642ee88247a6b4f2c0f9"),
        p_id: ObjectId("507f191e810c19729de860eb"),
        effected: "12",
        tested: "14255",
        negative: "1658451"
      },
      {
        _id: ObjectId("5e13642ee88247a6b4f2c0f1"),
        p_id: ObjectId("507f191e810c19729de860ea"),
        effected: "254",
        tested: "54851",
        negative: "158521541"
      }
    ]
  },
  {
    _id: ObjectId("5ab9cbe531c2ab715d52128a"),
    p_id: ObjectId("507f191e810c19729de860ea"),
    name: "hukke",
    mobile: 112466,
    area: "texas",
    mapped: [
      {
        _id: ObjectId("5e13642ee88247a6b4f2c0f9"),
        p_id: ObjectId("507f191e810c19729de860ea"),
        effected: "1222",
        tested: "3545621",
        negative: "354168512"
      }
    ]
  }
]

It has to be mapped with p_id. and the unmatched array should be dropped like this.

[
  {
    _id: ObjectId("5ab9cbe531c2ab715d42129a"),
    p_id: ObjectId("507f191e810c19729de860ea"),
    name: "elmaro",
    mobile: 112466,
    area: "texas",
    mapped: [
      {
        _id: ObjectId("5e13642ee88247a6b4f2c0f1"),
        p_id: ObjectId("507f191e810c19729de860ea"),
        effected: "254",
        tested: "54851",
        negative: "158521541"
      }
    ]
  },
  {
    _id: ObjectId("5ab9cbe531c2ab715d52128a"),
    p_id: ObjectId("507f191e810c19729de860ea"),
    name: "hukke",
    mobile: 112466,
    area: "texas",
    mapped: [
      {
        _id: ObjectId("5e13642ee88247a6b4f2c0f9"),
        p_id: ObjectId("507f191e810c19729de860ea"),
        effected: "1222",
        tested: "3545621",
        negative: "354168512"
      }
    ]
  }
]

Mongo version : 4.0.14

Upvotes: 0

Views: 256

Answers (1)

mickl
mickl

Reputation: 49945

Use $addFields to replace existing collection and $filter to remove non-matching sub-documents:

db.collection.aggregate([
    {
        $addFields: {
            mapped: {
                $filter: {
                    input: "$mapped",
                    cond: {
                        $eq: [ "$$this.p_id", "$p_id" ]
                    }
                }
            }
        }
    }
])

Mongo Playground

Upvotes: 1

Related Questions