入门基本操作
入门基本操作,常用的增删改查
MongoDB 插入文档
MongoDB 使用 insert() 方法向集合中插入文档,语法如下:
db.collection.insert(document)
例子:
db.getCollection("item").insert({user_id:1000, id:1001, amount:100})
MongoDB 删除文档
MongoDB remove()函数是用来移除集合中的数据。语法如下:
db.collection.remove(
\<query>,
{
justOne: \<boolean>,
writeConcern: \<document>
}
)
例子
db.getCollection("item").remove({user_id:1000, id:1001})
现在官方推荐使用 deleteOne() 和 deleteMany() 方法。
如删除集合下全部文档:
db.getCollection("item").deleteMany({})
删除道具id为1001的全部文档:
db.getCollection("item").deleteMany({id:1001})
删除用户道具id为1001的一个文档:
db.getCollection("item").deleteOne( {user_id:1000, id:1001} )
MongoDB 更新文档
MongoDB 使用 update() 方法来更新集合中的文档。语法如下:
db.collection.update(
\<query>,
\<update>,
{
upsert: \<boolean>,
multi: \<boolean>,
writeConcern: \<document>
}
)
例子:
只更新第一条记录:
db.getCollection("item").update( { "amount" : { $gt : 0} } , { $set : { "amount" : 100} } );
全部更新:
db.getCollection("item").update( { "amount" : { $gt : 0} } , { $set : {"amount" : 100} }, false, true );
添加一个字段:
db.getCollection("item").update( {} , { $set : {"amount" : 100} }, true, true );
删除一个字段:
db.getCollection("item").update( {} , { $unset : { "amount" : 100} }, false, true );
全部更新:(所有amount大于0的,amount都加1)
db.getCollection("item").update( {"amount" : { $gt : 0} } , { $inc : { "amount" : 1} }, false, true );
只更新第一条记录:
db.getCollection("item").update( { "id" : 1001, "amount" : { $gt : 0 } } , { $inc : { "amount" : 1} },false,false );
现在官方推荐使用 updateOne() 和 updateMany() 方法。
db.collection.updateOne() 向指定集合更新单个文档
db.collection.updateMany() 向指定集合更新多个文档
例子
db.getCollection("item").updateMany({user_id:10000,id:1002}, {$inc:{amount:NumberInt(100)}})
MongoDB 查询文档
MongoDB 查询文档使用 find() 方法。语法如下:
db.collection.find(query, projection)
例子:
db.getCollection("item").find({user_id:10000,id:1002})