1

In a document I have an object called farms and inside this object I would like to update key-value pairs in the following mannner. How would I do this?

$set:{"farms[${farm._id}]":{name:"a-farm", size:100}

the result would look like this(assuming farm._id = 12345)

farms:{"12345": {name"a-farm", size: 100}}
Sihoon Kim
  • 1,481
  • 2
  • 13
  • 32

1 Answers1

2

You can use $set and build your key dynamically using dot notation, try:

var farm = { _id: 12345 }
var path = "farms." + farm._id;
var documentId = ... // your document id

db.col.update({ _id: documentId  }, { $set: { [path]: { name:"a-farm", size:100 } }  })
mickl
  • 48,568
  • 9
  • 60
  • 89