|
|
|
|
|
|
|
|
|
Update operators for arrays
$push:add a value
$pop:remove one
value from collection from either right end of left end
$pushAll
$pull:remove
element from any position
$pullAll:remove
more than 1 irrespective of position
$addToSet:add
value if its unique
$push+$each+$position:
|
|
|
|
|
||
|
|
|
|
> db.array.insert({x:[1,2,3,4,5,6]})
WriteResult({
"nInserted" : 1 })
>
db.array.find().pretty()
{
"_id" :
ObjectId("55921d5c8e94c66f5795151b"),
"x" : [
1,
2,
3,
4,
5,
6
]
}
Push
>
db.array.update({"x":1},{$push:{"x":7}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
db.array.find().pretty()
{
"_id" :
ObjectId("55921d5c8e94c66f5795151b"),
"x" : [
1,
2,
3,
4,
5,
6,
7
]
}
Pull
>
db.array.update({"x":1},{$pull:{"x":7}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
db.array.find().pretty()
{
"_id" :
ObjectId("55921d5c8e94c66f5795151b"),
"x" : [
1,
2,
3,
4,
5,
6
]
}
>
Pull All
>
db.array.update({"x":1},{$pullAll:{"x":[1,2]}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
db.array.find().pretty()
{
"_id" :
ObjectId("55921d5c8e94c66f5795151b"),
"x" : [
3,
4,
5,
6
]
}
>
Pull with condition
>
db.array.update({"x":3},{$pull:{"x":{$gt:5}}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
db.array.find().pretty()
{ "_id"
: ObjectId("55921d5c8e94c66f5795151b"), "x" : [ 3, 4, 5 ]
}
>
|
|||
|
|
|
|
|
|
|
|
|
|
|
POP
>
db.array.update({"x":3},{$pop:{"x":-1}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
>
db.array.find().pretty()
{ "_id"
: ObjectId("55921d5c8e94c66f5795151b"), "x" : [ 4, 5, 6 ]
}
>
|
|
|||
|
|
|
|
|
|
|
|
|
|
Add to set
>
db.array.update({"x":3},{$addToSet:{"x":5}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
0 })
>
db.array.find().pretty()
{ "_id"
: ObjectId("55921d5c8e94c66f5795151b"), "x" : [ 3, 4, 5 ]
}
>
db.array.update({"x":3},{$addToSet:{"x":6}})
WriteResult({
"nMatched" : 1, "nUpserted" : 0, "nModified" :
1 })
>
db.array.find().pretty()
{
"_id" :
ObjectId("55921d5c8e94c66f5795151b"),
"x" : [
3,
4,
5,
6
]
}
|
|
|
|||
|
|
|
|
|
|
|
All my new technical experiments will be posted here for Future references and Knowledge sharing purpose. wrote it because I could've used it when I got started,
Tuesday, June 30, 2015
Array Operations in MongoDB
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment