mongodb笔记

入门基本操作

入门基本操作,常用的增删改查

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})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值