Fank Zhou
Fank Zhou

Reputation: 191

how can mongodb push a value into the specified array subscript

  1. my environment was mongodb 2.6.4

I need to insert an array into the specified array subscript. I tried it.

I need push a first array first , then insert an array into the specified array subscript.

db.a.update({_id:1},{$push:{'list':[1]}},upsert=true)
db.a.update({_id:1},{$push:{'list.2':2}},upsert=true)

I used the following a statement is incorrect.

db.a.update({_id:1},{$push:{'list.2':2}},upsert=true)

I want a statement to achieve it. what should I do?

Upvotes: 0

Views: 462

Answers (1)

Vishwas
Vishwas

Reputation: 7067

You should use $position operator in mongo. The index of $position starts from 0 so you should be careful with index. The query will be like following:

db.collection.find({_id:1},{$push:{list:{$each:[2],$position:1}}})

Upvotes: 2

Related Questions