一、匹配查询
1. 查询所有
> db.accounts.find()
{ "_id" : "account1", "name" : "alice", "balance" : 100 }
{ "_id" : ObjectId("5d7f25f4aecbd2bc0fa821b3"), "name" : "charlie", "balance" : 500 }
{ "_id" : ObjectId("5d7f25f4aecbd2bc0fa821b4"), "name" : "david", "balance" : 200 }
{ "_id" : { "name" : "david", "balance" : 200 }, "name" : "charlie", "balance" : 500 }
{ "_id" : { "balance" : 200, "name" : "david" }, "name" : "charlie", "balance" : 500 }
{ "_id" : { "balance" : "200", "name" : "david" }, "name" : "charlie", "balance" : 500 }
2. 查询所有+展示美化
> db.accounts.find().pretty()
3. 查询特定字段
> db.accounts.find({"name":"alice2"}).pretty()
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{
"_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"),
"name" : "alice2",
"balance" : 100
}
4. 查询主键
> db.accounts.find({"_id.name":"david"}).pretty()
{
"_id" : {
"name" : "david",
"balance" : 200
},
"name" : "charlie",
"balance" : 500
}
二、使用比较操作符
操作符 |
说明 |
eq |
等于 |
ne |
不等于 |
gt |
大于 |
gte |
大于等于 |
lt |
小于 |
lte |
小于等于 |
> db.accounts.find({"balance":{$lt:200}}).pretty()
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{
"_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"),
"name" : "alice2",
"balance" : 100
}
MongoDB 匹配查询和比较操作符