MongoDB常用基本操作查询文档

MongoDB查询访问使用find,以下主要讲解find查询的过滤条件如何使用


  1. 基本的查询语法
db.collection.find(query, projection)
  • query:查询条件
  • projection:使用投影操作符指定返回的键

  1. 等于,大于,小于条件查询
a. 等于查询 :
> db.collection.find({"age" : "18"})
等同于RDBMS: where age = '18'

b. 大于查询 $gt
> db.collection.find({"age" : {$gt : "18"}})
等同于RDBMS: where age > '18'

c. 大于等于查询 $gte
> db.collection.find({"age" : {$gte : "18"}})
等同于RDBMS: where age >= '18'

d. 小于查询 $lt
> db.collection.find({"age" : {$lt : "18"}})
等同于RDBMS: where age < '18'

e. 小于等于查询 $lte
> db.collection.find({"age" : {$lte : "18"}})
等同于RDBMS: where age <= '18'

  1. 逻辑与 $and 查询
    逻辑与有两种形式可以查询(逗号,) (逻辑运算符 $and)
> db.collection.find({"name":"sanzhang", "age":"18"})
> db.collection.find({$and:[{"name":"sanzhang"}, "age":"18"]})

等同于RDBMS: where name = ‘sanzhang’ and age = ‘18’

为了方便查看,我们格式化一把
逗号查询

> db.collection.find({
    "name" : "sanzhang",
    "age" : "18"
})

逻辑与查询

> db.collection.find({
    $and : [
        {"name" : "sanzhang"},
        {"age" : "18"}
    ]
})

建议使用第二种方式实现,更像OOP,而且比较容易与其他运算符做关联查询
以下mongodb查询统一格式化显示,方便观察结构


  1. 逻辑或 $or 查询
> db.collection.find({
    $or : [
        {"name" : "zhangsan"},
        {"name" : "lisi"}
    ]
})

等同于RDBMS: where name = ‘sanzhang’ or name = ‘lisi’


  1. $and 和 $or 关联查询
> db.collection.find({
    $and : [
        {"name" : "zhangsna"},
        {
            $or : [
                {"age" : "18"},
                {"age" : "28"}
            ]
        }
    ]
})

等同于RDBMS: where name = ‘sanzhang’ and (age = ‘18’ or age = ‘28’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值