3

I want to create new field in my document, lets call it "shelf", it will be an object. Next I want to make two $set operations - I want to put arrays named "Tom" and "Anna" into my "shelf".

The problem is that I can't match correct query to do that.

I'm using nodejs MongoDB driver.

var myid = 'Tom-Anna'
var TomArray = ["Tom"]
var AnnaArray = ["Anna"]

await db.collection('people').updateOne(
        { pairid: myid },
        { $set: { shelf: TomArray } },
        { upsert: true }
      )

await db.collection('people').updateOne(
        { pairid: myid },
        { $set: { shelf: AnnaArray } },
        { upsert: true }
      )

Finally, the "shelf" document containing only "AnnaArray", because it's overwriting previously added "TomArray".

I can't add "Tom" and "Anna" array to "shelf" at the same time because content of arrays are generated separately.

I was trying this code:

var name = 'Tom'
var array = ['Tom']
await db.collection('people').updateOne(
        { pairid: myid },
        { $set: { shelf[name]: array } },
        { upsert: true }
      )

But it's throwing following error:

{ $set: { shelf[name]: array } }, ^

SyntaxError: Unexpected token [

My goal is to set my field like JSON:

"shelf": { "Tom": ["Tom"], "Anna": ["Anna"] }

1 Answer 1

5

You can use dot notation to specify nested key name:

var name = 'Tom'
var array = ['Tom']
db.people.update({ pairid: 1 }, { $set: { [`shelf.${name}`]: array } })
Sign up to request clarification or add additional context in comments.

Comments

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.