1. 前言
在这篇文章中,我们将学习如何查询mongoDB中的数据。当我们把数据存储在mongoDB以后,我们需要把数据查询出来。毕竟CRUD操作中,查询操作在我们系统中是我们应用比较频繁的操作。我们需要应对不同的业务需求,构造合适的查询条件去查询我们想要的数据。我们需要去学习mongoDB给我们提供了哪些查询相关的语法和功能。在这里,我们使用mongodb自带的mongo shell(mongo shell是一个Javascript环境的mongodb客户端,支持js语法)来学习。
2. 准备
在开始之前,我们需要准备一下实验用的数据:
//启动mongo shell客户端
$ mongo//在这里我们使用test数据库,如果没有这个数据库,会自动创建
>use test//在users collection中插入6条用户数据
>db.users.insertMany(
[
{
_id:1,
name:"sue",
age:19,
type:1,
status:"P",
favorites: { artist:"Picasso", food: "pizza"},
finished: [17, 3],
badges: ["blue", "black"],
points: [
{ points:85, bonus: 20},
{ points:85, bonus: 10}
]
},
{
_id:2,
name:"bob",
age:42,
type:1,
status:"A",
favorites: { artist:"Miro", food: "meringue"},
finished: [11, 25],
badges: ["green"],
points: [
{ points:85, bonus: 20},
{ points:64, bonus: 12}
]
},
{
_id:3,
name:"ahn",
age:22,
type:2,
status:"A",
favorites: { artist:"Cassatt", food: "cake"},
finished: [6],
badges: ["blue", "red"],
points: [
{ points:81, bonus: 8},
{ points:55, bonus: 20}
]
},
{
_id:4,
name:"xi",
age:34,
type:2,
status:"D",
favorites: { artist:"Chagall", food: "chocolate"},
finished: [5, 11],
badges: ["red", "black"],
points: [
{ points:53, bonus: 15},
{ points:51, bonus: 15}
]
},
{
_id:5,
name:"xyz",
age:23,
type:2,
status:"D",
favorites: { artist:"Noguchi", food: "nougat"},
finished: [14, 6],
badges: ["orange"],
points: [
{ points:71, bonus: 20}
]
},
{
_id:6,
name:"abc",
age:43,
type:1,
status:"A",
favorites: { food:"pizza", artist: "Picasso"},
finished: [18, 12],
badges: ["black", "blue"],
points: [
{ points:78, bonus: 8},
{ points:57, bonus: 7}
]
}
]
)
View Code
3. 基本查询
MongoDB提供了db.collection.find()方法来执行查询操作。find方法接受两个参数:一个查询条件,一个是投影的字段。这两个参数都不是必须的,如果省略了查询条件,则默认列出collection中的所有文档。
db.users.find()//这个和上面的语句是等价的
db.users.find({})
3.1 等值查询
通过find()方法来执行等值查询的时候,可以通过{:}的方式来指定查询条件,这个条件表示在collection中查询满足field的值为value的所有文档。假设我们需要查找所有status是'A'的用户,我们可以这么查询:
db.users.find({status: 'A'})
查询结果
{ "_id" : 3, "name" : "ahn", "age" : 22, "type" : 2, "status" : "A", "favorites" : { "artist" : "Cassatt", "food" : "cake" }, "finished" : [ 6 ], "badges" : [ "blue", "red" ], "points" : [ { "points" : 81, "bonus" : 8 }, { "points" : 55, "bonus" : 20} ] }
{"_id" : 6, "name" : "abc", "age" : 43, "type" : 1, "status" : "A", "favorites" : { "food" : "pizza", "artist" : "Picasso" }, "finished" : [ 18, 12 ], "badges" : [ "black", "blue" ], "points" : [ { "points" : 78, "bonus" : 8 }, { "points" : 57, "bonus" : 7 } ] }
3.2 操作符查询
mongodb支持使用操作符来构造查询条件,比如比较操作符,如$gt,$lt等。使用操作符的查询条件通过{: {:}}来表示。假设我们要查询age超过22的用户,可以这么做:
db.users.find({age: {$gt: 22}})
查询结果
{ "_id" : 2, "name&#