1

I am writing generic code which will do both add and update as an atomic operation therefore used findOneAndUpdate. My flatten data with array is inserted as object instead of array. Following are details.

db.test.findOneAndUpdate({"saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083"},{$set:{"price.priceTier.0.unitSold": 1,}}, {upsert:true})
db.test.find()
{ "_id" : ObjectId("5b0173fbcd90c934727269ac"), "saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083", "price" : { "priceTier" : { "0" : { "unitSold" : 1 } } } }

How can I make sure that {$set:{"price.priceTier.0.unitSold": 1,}} should add as an array as below?

{ "_id" : ObjectId("5b0173fbcd90c934727269ac"), "saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083", "price" : { "priceTier" : [{ "unitSold" : 1 } ]} }

Since I am trying to write generic code and using flat npm module to flatten my input data to convert into mongodb query therefore I am trying not to change my query if possible. Please help.

joy
  • 3,669
  • 7
  • 38
  • 73
  • You need to actually overwrite all of `priceTier` at least and maybe even `price`. How bad exactly is this? Bottom line being we first need to `$set` as an array before you can begin to work with it as an array again. But I'd like to get more insight into the actual scope of the problem, being whether there are actually "multiple" entries that should be under an array and not such "one" with simply a 0 index. – Neil Lunn May 20 '18 at 21:42
  • Thank you, I agree that I need to fist `$set` as an array then only I can use index based query. So as an alternative, I used the second point you mentioned to overwrite all of `priceTier`. I used `mongo-flatten` npm module to flatten my payload. It doesn't change array therefore I was able to use `findOneAndUpdate` with `upsert` by one code. – joy May 21 '18 at 17:11

1 Answers1

0
db.test.findOneAndUpdate({"saleId" : "7d55acf0-5bc2-11e8-b3e5-c51df4c55083"},{$set:{"price.priceTier":{$push:{"unitSold": 1}}}, {upsert:true})
mohammad Naimi
  • 2,259
  • 1
  • 5
  • 15