简体   繁体   中英

how to Increment optional sub-fields using $inc operator?

this are sample documents of the collection,

  {
    _id: ObjectId("637f1128d8298d42bae0d4fc"),
    name: 'Iska Paphat',
    age: 8,
    cat: { name: 'Malone Poppelhoffen', age: 7 }
  },
  {
    _id: ObjectId("637f1128d8298d42bae0d4fd"),
    name: 'Elbow Frank',
    age: 67
  },
  {
    _id: ObjectId("637f1128d8298d42bae0d4fe"),
    name: 'Frank Frank',
    age: 49,
    cat: { name: 'Pirate Yolanda', age: 4 }
  },
  {
    _id: ObjectId("637f1128d8298d42bae0d4ff"),
    name: 'Fluffy Yolanda',
    age: 66
  },

I'm trying to increment age and cat.age by 1, using db.people.updateMany({},{$inc:{age:1,'cat.age':1}}) , this command adds {cats:{age:1}} in fields which has no cat subfields.

{
    _id: ObjectId("637f03bcd8298d42bae0d110"),
    name: 'Elbow Pirate',
    age: 5,
    cat: { age: 1 }
  },
  {
    _id: ObjectId("637f03bcd8298d42bae0d111"),
    name: 'Malone Foxton',
    age: 45,
    cat: { age: 1 }
  },
  {
    _id: ObjectId("637f03bcd8298d42bae0d112"),
    name: 'Fluffy Poppelhoffen',
    age: 1,
    cat: { age: 1 }
  },

how to $inc both cat's age and person age without adding cat field in single query ?

You want to be using pipelined updates for this. this allows us to incorporate some more complex logic, in this case only increment the age field if the cat exists.

db.people.updateMany({},
[
  {
    $set: {
      age: {
        $sum: [
          "$age",
          1
        ]
      },
      cat: {
        $cond: [
          {
            $eq: [
              "$cat",
              undefined
            ]
          },
          "$$REMOVE",
          {
            $mergeObjects: [
              "$cat",
              {
                age: {
                  $sum: [
                    "$cat.age",
                    1
                  ]
                }
              }
            ]
          }
        ]
      }
    }
  }
])

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