最近在弄MongoDB,总结了一下操作的方法, MongoDB 还是很方便的,写出来的PHP语句非常精简,感觉是直接对数据进行操作,是PDO都无法超越的。同时,可以随时更改的数据结构极大地方便了软件的初期开发。但是对软件的设计进行规划也是很有必要的。
Mongodb 如果存在则update如果不存在则insert的方法,使用 upsert 旗帜
例子:
db.inventory.update( { type: "book", item : "journal" }, { $set : { qty: 10 } }, { upsert : true } )
往集合批量添加元素需要使用$each
> db.xtxt.update({"asdf":11}, { $push : {"group":[5,4,6,8] } },{upsert: true} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.xtxt.find() { "_id" : ObjectId("53b2e2f39f1c90bdf306da98"), "asdf" : 11, "group" : [ { "wk" : "asdf", "ee" : 5 }, { "wk" : "asddf", "ee" : 25 }, [ 5, 4, 6, 8 ] ] } { "_id" : ObjectId("53b2db39c3a9fcd1793c9b1e"), "asdf" : 12, "group" : [ ] } > db.xtxt.update({"asdf":11}, { $pop : {"group": 1 } } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.xtxt.find() { "_id" : ObjectId("53b2e2f39f1c90bdf306da98"), "asdf" : 11, "group" : [ { "wk" : "asdf", "ee" : 5 }, { "wk" : "asddf", "ee" : 25 } ] } { "_id" : ObjectId("53b2db39c3a9fcd1793c9b1e"), "asdf" : 12, "group" : [ ] } > db.xtxt.update({"asdf":11}, { $push : {"group":{$each: [5,4,6,8] } } },{upsert: true} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.xtxt.find() { "_id" : ObjectId("53b2e2f39f1c90bdf306da98"), "asdf" : 11, "group" : [ { "wk" : "asdf", "ee" : 5 }, { "wk" : "asddf", "ee" : 25 }, 5, 4, 6, 8 ] } { "_id" : ObjectId("53b2db39c3a9fcd1793c9b1e"), "asdf" : 12, "group" : [ ] } >
不过更方便的是使用 $pushAll
> db.xtxt.update({"asdf":11}, { $pushAll : {"group":[0,888,555,5,4,6,8] } },{upsert: true} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.xtxt.find() { "_id" : ObjectId("53b2e2f39f1c90bdf306da98"), "asdf" : 11, "group" : [ { "wk" : "asdf", "ee" : 5 }, { "wk" : "asddf", "ee" : 25 }, 5, 4, 6, 8, 0, 888, 555, 5, 4, 6, 8 ] } { "_id" : ObjectId("53b2db39c3a9fcd1793c9b1e"), "asdf" : 12, "group" : [ ] } >
更新集合里面的内容可以使用$elemMatch ,并且配合 $
> db.xtxt.update( { "asdf":11, "group" : {$elemMatch : {"wk": "asdf"} } }, { $set : {"group.$.ee":100 }} ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.xtxt.find() { "_id" : ObjectId("53b2e2f39f1c90bdf306da98"), "asdf" : 11, "group" : [ { "wk" : "asdf", "ee" : 100 }, { "wk" : "asddf", "ee" : 25 }, 5, 4, 6, 8, 0, 888, 555, 5, 4, 6, 8 ] } { "_id" : ObjectId("53b2db39c3a9fcd1793c9b1e"), "asdf" : 12, "group" : [ ] } >