1.1 查询全部
db.getCollection(‘orderInfo’).find({})
db.orderInfo.find();
1.2 条件查询基本
语法: db.[documentName].find ({条件},{键指定})
1.2.1 根据_id查询
db.orderInfo.findOne( {"_id" : ObjectId("5a40af6e923ea32829f21b38")})
查询出全部列
1.2.2 根据其它document查询
//orderId=201712251003
db.orderInfo.find({"orderId":"201712251003"});
查询出全部列
1.2.3 多条件查询
//orderId = orderId and amount=98.78
db.orderInfo.find({"orderId":"201712251003","amount":98.78});
1.2.4 查询列出指定字段
//select orderId,amount from table where orderId = orderId and amount=98.78
db.orderInfo.find({"orderId":"201712251003","amount":98.78},{orderId:1,_id:0,amount:1});
此时只列出了orderId和amount,不列出_id
1.2.5 比较查询
lt<; lte <=; gt>; gte >=;$ne !=
//orderId=201712251003 and (amount>=25 and amount<=100)
db.orderInfo.find({"orderId":"201712251003",amount:{$gte:25,$lte:100}});
1.2.6 包含或不包含
in或 nin
//_id in(ObjectId("5a409486fb824a6ee0cb6ad3"),ObjectId("5a4096fefb824a4dd075f32c"))
db.orderInfo.find({_id:{$in:[ObjectId("5a409486fb824a6ee0cb6ad3"),ObjectId("5a4096fefb824a4dd075f32c")]}})
//totalAmount in(100,200)
db.orderInfo.find({totalAmount:{$in:[100,200]}})
1.2.7 OR查询
//_id=ObjectId("5a4096fefb824a4dd075f32c") and totalAmount=100
db.orderInfo.find({$or:[{_id:ObjectId("5a4096fefb824a4dd075f32c")},{totalAmount:100}]})
//_id=ObjectId("5a4096fefb824a4dd075f32c") and (amount>=25 and amount<=100)
db.orderInfo.find({$or:[{_id:ObjectId("5a4096fefb824a4dd075f32c")},{totalAmount:{$gte:25,$lte:100}}]})
1.2.8 null
//commentsNew2 is null
db.orderInfo.find({commentsNew2:null});
1.2.9 not
{ field: { $not: { } } }
not和 nin的区别是 not可以用在任何地方儿 nin是用到集合上的
//totalAmount !< 100
db.orderInfo.find({totalAmount:{$not:{$lte:100}}})
//orderName not like "测试%"
db.orderInfo.find({orderName:{$not:/测试*/i}})
$not配合其它表达式以及正则表达式,作用强大.
db.orderInfo.find({goosNames:{$size:3}})
1.3 正则
//orderNo以2017开头的
db.orderInfo.find({"orderNo":/2017*/i})
1.4 数组查询
//document中的值如下:
"goosNames" : [
"mongodbbook",
"springbootbook",
"mybatisbook"
]
1.4.1 $all
{ <field>: { $all: [ <value1> , <value2> ... ] } }
The $all operator selects the documents where the value of a field is an array that contains all the specified elements
查询的值中必须包含的条件中的全部的值(无论顺序)
//document中的值如下:
"goosNames" : [
"mongodbbook",
"springbootbook",
"mybatisbook"
]
//能差存储结果
db.orderInfo.find({goosNames:{$all:["springbootbook","mybatisbook"]}})
//查询不出结果
db.orderInfo.find({goosNames:{$all:["springbootbook","mybatisbook1"]}})
1.4.2 数组index
数组的索引位置,index从0开始
//document中的值如下:
"goosNames" : [
"mongodbbook",
"springbootbook",
"mybatisbook"
]
//goosNames[1]=springbootbook
db.orderInfo.find({"goosNames.1":"springbootbook"} )
1.4.3 数组size
//goosNames.length=3
db.orderInfo.find({goosNames:{$size:3}})
参考:
MongoDB学习笔记(查询)