Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

mongodb - How to use $addFields in mongo to add elements to just existing documents?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$$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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...