Home > Back-end >  MongoDB would like to enter and update a key in an object for the first time
MongoDB would like to enter and update a key in an object for the first time

Time:08-08

This is the end result I would like to get.

{
    '_id': '2022-08-06',
    'users': [
        {
            'id': '345456',
            point: 1,
        },
    ],
};

I'm trying these, but it doesn't work. Thank you very much for your reply.

client.db(dbProject).collection('test').updateOne({ '_id': data.id, users: { $elemMatch: { id: data.id2 } } })
client.db(dbProject).collection('test').findOneAndUpdate(
    {
        '_id': data.id,
        users: { $elemMatch: { id: data.id2 } },
    },
    { $addToSet: { 'users': { id: data.id } }, $inc: { 'users.point': decimal(String(data.point)) } },
    {
        upsert: true,
    })

CodePudding user response:

You can achieve this by using the aggregation pipeline update syntax, like so:

client.db(dbProject).collection("test").updateOne(
{
   "_id": data.id
},
[
  {
    $set: {
      users: {
        $ifNull: [
          "$users",
          []
        ]
      }
    }
  },
  {
    "$set": {
      "users": {
        $concatArrays: [
          {
            $map: {
              input: "$users",
              in: {
                $mergeObjects: [
                  "$$this",
                  {
                    $cond: [
                      {
                        $eq: [
                          "$$this.id",
                          data.id2
                        ]
                      },
                      {
                        point: {
                          $sum: [
                            "$$this.point",
                            1
                          ]
                        }
                      },
                      {}
                    ]
                  }
                ]
              }
            }
          },
          {
            $cond: [
              {
                $in: [
                  data.id2,
                  "$users.id"
                ]
              },
              [],
              [
                {
                  id: data.id2,
                  point: 1
                }
              ]
            ]
          }
        ]
      }
    }
  },
  
],
{
  "upsert": true
})

Mongo Playground

  • Related