简体   繁体   中英

MongoDB Aggregation - How to condition for $set

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM