3

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"
            }
    })
9
  • what is your db version ? Commented Apr 16, 2020 at 14:32
  • structure of $$company? Commented Apr 16, 2020 at 14:50
  • @whoami, DB version is 4.2.0 Commented Apr 16, 2020 at 17:31
  • @mehta-rohan, I update the question. It's companyId not a company. Commented Apr 16, 2020 at 17:32
  • Does this answer your question? Update MongoDB field using value of another field Commented Apr 16, 2020 at 17:34

1 Answer 1

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']]}}}])
Sign up to request clarification or add additional context in comments.

2 Comments

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:"
@JaySojitra : In the past I’ve observed robo3T has issues using aggregation pipeline in updates especially with updateMany() & updateOne(), just try with update() !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.