Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

82
Views
MongoDB would like to enter and update a key in an object for the first time

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,
    })
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!