增加
- 单条插入
db.user.insert({
"name": "Mac1",
"serialNumber":NumberLong("1000000000000001"),
"scoreMap":{
"english": {
"score": 87
},
"chinese": {
"score": 99
}
},
"birthday":"0322",
"age":15
});
插入结果如下
image.png
- 多条插入
db.user.insertMany([{
"name": "Macmac",
"serialNumber": NumberLong("1000000000000002"),
"scoreMap": {
"math": {
"score": 73
},
"chinese": {
"score": 62
}
},
"checks": [{
"month": 1,
"score": "A"
}, {
"month": 2,
"score": "B"
}],
"age": 17
}, {
"name": "macMac",
"serialNumber": NumberLong("1000000000000003"),
"scoreMap": {
"sports": {
"score": 88
},
"chinese": {
"score": 95
}
},
"checks": [{
"month": 1,
"score": "S"
}, {
"month": 2,
"score": "C"
}, {
"month": 3,
"score": "S"
}],
"age": 18
}]);
结果如下
image.png
查询
假设我们有个mysql数据库也包含个user表,也包含name、serialNumber、age这些字段,我们来看下sql和mongo的语法差异
sql | mongo | 含义 |
---|---|---|
select * from user where 1=1; | db.user.find(); | 查询全部 |
select * from user where name = "Mac"; | db.user.find({"name":"Mac"}); | 查询姓名为Mac的 |
select * from user where age < 17 | db.user.find({"age":{$lt:17}}); | 查询年龄小于17 |
select * from user where age < = 17 | db.user.find({"age":{$lte:17}}); | 查询年龄小于等于17 |
select * from user where age > 17 | db.user.find({"age":{$gt:17}}); | 查询年龄大于17 |
select * from user where age >= 17 | db.user.find({"age":{$gte:17}}); | 查询年龄大于等于17 |
select * from user where age <> 17 | db.user.find({"age":{$ne:17}}); | 查询年龄不等于17 |
select * from user where name like "Mac%"; | db.user.find({"name":/^Mac/}); 或 db.user.find({"name":{ $regex:/^Mac/}}); |
查询名字以Mac开头的。在mongo中,db.user.find({"name":/^Mac/i});加i代表忽略大小写,也意味着mac mAC MAC等这样开头的也会被查询出来 |
select * from user where name like "%Mac"; | db.user.find({"name":/Mac$/}); 或 db.user.find({"name":{ $regex:/Mac$/}}); |
查询名字以Mac结尾的 |
select * from user where name like "%Mac%"; | db.user.find({"name":/Mac/}); 或 db.user.find({"name":{ $regex:/Mac/}}); |
查询名字包含Mac的 |
select * from user where age < 18 and name like "Mac%"; | db.user.find({"age":{$lt:18},"name":/Mac/}); 或 db.user.find({$and:[{"age":{$lt:18},"name":/Mac/}]}); |
查询年龄小于18的 并且 名字以Mac开始的 |
select * from user where age < 17 or age >17; | db.user.find({$or:[{"age":{$lt:17}},{"age":{$gt:17}}]}); | 查询年龄小于17或者大于17的 |
select * from user where name = 'Mac1' and (age < 17 or age >17); | db.user.find({"name":"Mac1",$or:[{"age":{$lt:17}},{"age":{$gt:17}}]}); | 查询名字为Mac1并且年龄小于17或者大于17的 |
网友评论