Home > OS >  MongoDB Aggregation - How to condition for $set
MongoDB Aggregation - How to condition for $set

Time:12-08

I am unwinding a lookup joined by { preserveNullAndEmptyArrays: true } option to include documents whose sizes field is null, missing, or an empty array. But in my case, I need to join nested lookup and the output result is not as I expected.

Specifically, I am being to set a new buyer field by the $set operator from lookup but if this lookup is null or empty array it will return [ { } ] and I don't want that. How can I replace [ { } ] with empty array?

The result I got:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "buyers": [
      {
        "_id": ObjectId("5a934e000102030405000003"),
        "buyer": {
          "_id": ObjectId("5a934e000102030405000004"),
          "display_name": "Phineas",
          "user_id": "123"
        },
        "post_id": 1,
        "user_id": "123"
      }
    ],
    "content": "content book 1",
    "title": "title book 1"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "buyers": [
      {}
    ],
    "content": "content book 3",
    "title": "title book 3"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "buyers": [
      {}
    ],
    "content": "content book 2",
    "title": "title book 2"
  }
]

The result that I expected:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "buyers": [
      {
        "_id": ObjectId("5a934e000102030405000003"),
        "buyer": {
          "_id": ObjectId("5a934e000102030405000004"),
          "display_name": "Phineas",
          "user_id": "123"
        },
        "post_id": 1,
        "user_id": "123"
      }
    ],
    "content": "content book 1",
    "title": "title book 1"
  },
  {
    "_id": ObjectId("5a934e000102030405000002"),
    "buyers": [],
    "content": "content book 3",
    "title": "title book 3"
  },
  {
    "_id": ObjectId("5a934e000102030405000001"),
    "buyers": [],
    "content": "content book 2",
    "title": "title book 2"
  }
]

Now you can see my code in the Mongo playground link: https://mongoplayground.net/p/qiC7FySejxF

CodePudding user response:

Comparing your actual output and MongoDB Playground link, I believe that you miss out the $unset stage.

{
  $unset: "buyers.buyers"
}

While after the $unset stage, you can add $set stage to update the buyers field by filtering the document which is not empty document via $filter.

{
  $set: {
    buyers: {
      $filter: {
        input: "$buyers",
        cond: {
          $ne: [
            "$$this",
            {}
          ]
        }
      }
    }
  }
}

Demo @ Mongo Playground

  • Related