Mongodb $ 关键字 $ 修改器

MongoDB $ 数字关键字

等于

: 在MongoDB中什么字段等于什么值其实就是 " : " 来搞定 比如 "name" : "lin"

$eq 和上边查询结果是一样的

大于 在MongoDB中的 大于 > 号 我们用 : $gt 比如

大于等于 在MongoDB中的 大于等于 >= 号 我们用 : $gte

小于 在MongoDB中的 小于 < 号 我们用 : $lt

小于等于 在MongoDB中的 小于等于 <= 号 我们用 : $lte

MongoDB $ 查询关键字

$or

查询条件中什么或者什么条件时候

db.collection.find({$or:[{"username":"傻了吧嗒"},{"username":"糖炒栗子"}]}) 查询 username 是 "傻了吧嗒" 和 "糖炒栗子" 的数据。

$in

查询 "year" 满足 在[2018,2019,2020]中的数据

db.collection.find({"year":{$in:[2018,2019,2020]}}) # 满足一个条件即可

$all

查询数据中 year 满足所有列表的数据

db.collection.find({year:{$all:[2018,2019,2020,2021]}}) #子集查询

MongoDB $ 修改器

MongoDB的 update修改器: $inc $set $unset $push $pull

$inc

db.collection.update({"username":"傻了吧嗒"},{$inc:{"age":10}}) # 让 username 为 傻了吧嗒 的人的 age 增加10岁

db.collection.update({"username":"傻了吧嗒"},{$inc:{"age":-10}}) # 让 username 为 傻了吧嗒 的人的 age 减少10岁

$set

用于更新数据,没有就自动添加一条

db.collection.update({"username":"傻了吧嗒"},{$set:{"age":100}}) # 让 username 为 傻了吧嗒 的人的 age 更新为100岁

$unset

用来删除Key(field)的, 相当于 关系型数据库中删除了字段

db.collection.update({"username":"傻了吧嗒"},{$unset:{"age":100}}) # 删除 username 为 傻了吧嗒 的人的 age 字段

$push

用来对Array (list)数据类型进行增加新元素的,相当于Python中 list.append() 方法

首先 db.collection.updateMany({},{$set:{"test_list":[1,2,3,4]}}) # 为所有数据都添加一个test_lsit列表

接下来我们就要队列表进行添加了: 将 "username" 为 傻了吧嗒 的Document 中"test_list" 添加一个 5

db.collection.update({"username":"傻了吧嗒"},{$push:{"test_list":5}}) # \(push 是在 Array(list) 的尾端加入一个新的元素 {\)push : {"test_list" : 5}}

$pull

$pull 就是指定删除Array (list)数据类型中的某一个元素

db.collection.update({"username":"傻了吧嗒"},{$pull:{"test_list":4}}) # 将 "username" 为 傻了吧嗒 的Document 中"test_list" 删除一个 4

注:如果 Array (list)数据类型中 如果有多个4会全部删掉!

所以,只要满足条件, 就会将Array中所有满足条件的数据全部清除掉

$pop

删除"username" 等于 傻了吧嗒 test_list 的最后一个元素

db.collection.update({"username":"傻了吧嗒"},{$pop:{"test_list":-1}}) # 删除 "username" 为 傻了吧嗒 的Document 中"test_list" 的第一个元素

db.collection.update({"username":"傻了吧嗒"},{$pop:{"test_list":1}}) # 删除 "username" 为 傻了吧嗒 的Document 中"test_list" 的最后一个元素

{$pop:{"test_list" : -1}} -1 代表最前面, 1 代表最后边 (和Python正好相反)

猜你喜欢

转载自www.cnblogs.com/lskreno/p/11653272.html
今日推荐