比较查询运算符
小于 age: { $lt: 30} 语法 {field: {$lt: value} } 小于等于$lte
大于 age: { $gt: 30} 大于等于 $gte
相等 age: { $eq: 30} age: { $eq: [30, 50] }
不等 age: { $ne: 30} 包括不含age的文档
in运算 age:{$in: [20, /^b/, /正则/ ]} 但不能在正则里面用in运算
no in运算 age:{$in: [20, 30]} 包括不含age的文档
更新运算符
最后更新时间 $currentDate: { lastDate: true } 值有true、"timestamp"、"date"
和数值相加减 $inc: { a: 6, b: -2 } 这个是字段a + 6, 字段b - 2
相乘 $mul
集合中的集合key:"size.h"
重命名:$rename: { "lowScore": "score" } 如果lowScore不存在则无动作
取小的更新字段 $min: { lowScore: 250 } 比如lowScore原来的值是300,更新后是250
取大的更新字段 $max: { lowScore: 250 } 比如lowScore原来的值是300,更新后是300
需更新的集合 $set: { a: 6, b: -2 }
更新引起插入时合 $setOnInsert: { a: 6, b: -2 } 如果只有更新没有插入时没有动作
将匹配到的字段值换为null $unset: { a: ‘’, b: ‘’ } ‘’写什么值不影响运算
查询:
db.user.find() 相当于:SELECT * FROM tablename
db.getCollection("user").find({key:value}) SELECT * FROM tablename WHERE key = ?
db.user.find({
$and: [
{ age: { $lt: 30} },
{ $or: [ { name: "notebook" }, { name: "journal" } ] }
]
})
相当于 SELECT * FROM tablename WHERE age < 30 AND ( name = “notebook” OR name = “journal” )
插入一个:db.集合名称.insertOne()
db.user.insertOne(
{ name: "notebook", age: 50, size: { h: 8.5, w: 11, uom: "in" }, tag: ["A", "C"] }
);
插入多个:db.集合名称.insertMany()
db.getCollection("user").insertMany([
{ name: "journal", age: 25, size: { h: 14, w: 21, uom: "cm" }, tag: ["A", "B"] },
{ name: "notebook", age: 50, size: { h: 8.5, w: 11, uom: "in" }, tag: ["A", "C"] }
]);
更新一个(其中alias、lastDate原表没有,为新增字段):
updateOne(查询条件, 更新文本 [, 操作]) 比如 { upsert : true } 表示没查到则新增
db.getCollection("user").updateOne(
{name: "su" },
{
$set: { "size.h": 12, "alias": "alias" },
$currentDate: { lastDate: true }
}
)
更新多个:
db.user.updateMany(
{age: 50 },
{
$set: { "size.h": 12, "alias": "alia1" },
$currentDate: { lastDate: true }
}
);
替换文档:没有一次替换多个的
db.user.replaceOne(
{age: 50 },
{
size: {t: 12}, "alias": "alia1"
}
);
删除所有:db.getCollection("user").deleteMany({})
按条件:db.user.deleteMany({age: 50})
删除一个:db.user.deleteOne({age: 50})
删除第一个:db.user.deleteOne({})