mongodb简单操作
1、使用insert完成插入操作
> db.fruit.insertOne({name:"apple"})
{
"acknowledged" : true,
"insertedId" : ObjectId("604cb3d6bf7f9d9878bde368")
}
> db.fruit.insertMany([
... {name:"apple"},
... {name:"pear"},
... {name:"orange"}
... ])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("604cb42fbf7f9d9878bde369"),
ObjectId("604cb42fbf7f9d9878bde36a"),
ObjectId("604cb42fbf7f9d9878bde36b")
]
}
>
2、使用find查询文档
> db.fruit.find()
{ "_id" : ObjectId("604cb3d6bf7f9d9878bde368"), "name" : "apple" }
{ "_id" : ObjectId("604cb42fbf7f9d9878bde369"), "name" : "apple" }
{ "_id" : ObjectId("604cb42fbf7f9d9878bde36a"), "name" : "pear" }
{ "_id" : ObjectId("604cb42fbf7f9d9878bde36b"), "name" : "orange" }
>
- 关于find:
- find是Mongodb中查询数据的基本指令,相当于SQL中的SELECT
- find返回的是游标
- find示例
- db.movies.find({"year":1975})//单条件查询
- db.movies.find({"year":1989,"title":"Batman"})//多条件and查询
- db.movies.find({$and:[{"title":"Batman"},{"category":"action"}]})//and的另一种形式
- db.movies.find({$or:[{"year":1989},{"title":"Batman"}})//多条件or查询
- db.movies.find({"title":/^B/})//按正则表达式查找
- 查询条件对照表
SQL | MQL |
a==1 | {a:1} |
a<>1 | {a:{$ne:1}} |
a>1 | {a:{$gt:1}} |
a>=1 | {a:{$gte:1}} |
a<1 | {a:{$lt:1}} |
a<=1 | {a:{$lte:1}} |
- (>) 大于 - $gt
- (<) 小于 - $lt
- (>=) 大于等于 - $gte
- (<= ) 小于等于 - $lte
- 查询逻辑对照表
SQL | MQL |
a=1 AND b=1 | {a:1,b:1}或{$and:[{a:1},{b:1}]} |
a=1 OR b=1 | {$or:[{a:1},{b:1}]} |
a IS NULL | {a:{$exists:false}} |
a IN (1,2,3) | {a:{$in:[1,2,3]}} |
- $ne:不存在或存在不等于
- $in:存在并在指定数组中
- $nin:不存在或不存在指定数组中
- $and 匹配全部条件
- $or:匹配两个或多个条件中的一个
- 使用find搜索子文档
- find支持使用"find.sub_field"的形式查询子文档,假定有一个文档
> db.fruit.insertOne({
... name:"apple",
... from:{
... country:"china",
... province:"Guangdon"
... }
... })
- 考虑以下查询的意义
- db.fruit.find({"from.country":"China"})错误写法
- db.fruit.find({"from":{country:"China"})
- 使用find搜索数组
- find支持对数组中的元素进行搜索,假设有一个文档:
> db.fruit.insert([
... {"name":"Apple",color:["red","green"]},
... {"name":"Mango",color:["yellow","green"]}
... ])
- 考虑以下查询的意义:
- db.fruit.find({color:"red"})
- db.fruit.find({$or:[{color:"red"},{color:"yellow"}]})