Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to add a new field to an existing document by using a combination of both $ifnull and $cond but an empty document is always added at the end.

Configuration:

    [
      {
        line: "car",
        number: "1",
        category: {
          FERRARI: {
            color: "blue"
          },
          LAMBORGHINI: {
            color: "red"
          }
        }
      },
      {
        line: "car",
        number: "2",
        category: {
          FERRARI: {
            color: "blue"
          }
        }
      }
    ]

Query approach:

db.collection.aggregate([
  {
    $match: {
      $and: [
        { line: "car" },
        { number: { $in: ["1", "2"] } }
      ]
    }
  },
  {
    "$addFields": {
      "category.LAMBORGHINI.number": {
        $cond: [
          { "$ifNull": ["$category.LAMBORGHINI", false] },
          "$number",
          "$$REMOVE"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      CATEGORIES: {
        $addToSet: "$category.LAMBORGHINI"
      }
    }
  }
])

Here is the link to the mongo play ground:

https://mongoplayground.net/p/RUnu5BNdnrR

I tried the mentioned query but I still get that ugly empty set added at the end.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

$$REMOVE will remove last field/key, from your field category.LAMBORGHINI.number the last field is number that is why it is removing number from the end, you can try another approach,

  • specify just category.LAMBORGHINI, if condition match then it will return object of current category.LAMBORGHINI and number object after merging using $mergeObjects
  {
    "$addFields": {
      "category.LAMBORGHINI": {
        $cond: [
          { "$ifNull": ["$category.LAMBORGHINI", false] },
          {
            $mergeObjects: [
              "$category.LAMBORGHINI",
              { number: "$number" }
            ]
          },
          "$$REMOVE"
        ]
      }
    }
  }

Playground


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...