2

I have one mongodb object like below :

{
    "_id" : ObjectId("5e54934b2dfddc1826223bbb"),
    "sellProducts" : {
        "products" : []
    },
    "sellServices" : {
        "services" : []
    },
    "categories" : [],
    "status" : "Published",
    "tags" : [],
    "dateRange" : [],
    "membershipRequired" : false,
    "usersAttending" : [],
    "cities" : [],
    "companies" : [ 
        ObjectId("5db1c84ec10c45224c4b95fd"),
    ],
    "companyId" : ObjectId("5db1c84ec10c45224c4b95fd"),
    "jobProfile" : [ 
        ObjectId("5e549339a3ad20c97b7b0c7d")
    ],
    "fundingBy" : []
}

Now I want to update the same record by pushing the value of the companyId field into the array of companies. How can I do that?

I tried below query but It didn't work :

db.getCollection('posts').update({_id: ObjectId("5e54934b2dfddc1826223bbb")},
    {
        $push: 
            {
                companies: "$$companyId"
            }
    })
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
Jay Sojitra
  • 172
  • 1
  • 9

1 Answers1

3

As you're using MongoDB version 4.2 where you can actually run aggregation pipeline in updates, Try below query :

/** As `$push` doesn't work in aggregation as update operator
 * You can use `$addFields` or `$set` to re-create 'companies' field by merging 'companies' array with array converted 'companyId' field
 * which would leave 'companies' as an array with existing elements + companyId */

db.getCollection('posts').updateOne({_id: ObjectId("5e54934b2dfddc1826223bbb")},
         [{$addFields : {companies: {$concatArrays: ['$companies',['$companyId']]}}}])
whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • 1
    Thank you for your support. But when I execute your script it gives me below error: "Failed to execute script. Error: the update operation document must contain atomic operators Details:" – Jay Sojitra Apr 17 '20 at 06:41
  • 3
    @JaySojitra : In the past I’ve observed robo3T has issues using aggregation pipeline in updates especially with updateMany() & updateOne(), just try with update() !! – whoami - fakeFaceTrueSoul Apr 17 '20 at 06:43