MongoDB 常用操作笔记 find ,count, 大于小于不等, select distinct, groupby,索引


本博客将列举一些常用的MongoDB操作,方便平时使用时快速查询,如find, count, 大于小于不等, select distinct, groupby等

1. 大于,小于,大于或等于,小于或等于,不等于

  • $gt: 大于
  • $lt: 小于
  • $gte: 大于或等于
  • $lte: 小于或等于
  • $ne: 不等于
// greater than : field > value
db.collection.find({ "field" : { $gt: value } } ); 

// less than : field < value
db.collection.find({ "field" : { $lt: value } } ); 

// greater than or equal to : field >= value
db.collection.find({ "field" : { $gte: value } } ); 

// less than or equal to : field <= value
db.collection.find({ "field" : { $lte: value } } ); 

// not equal: field != value
db.collection.find( { "field" : { $ne : value } } );

也可以合并在一条语句内:

// value1 < field < value
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); 

2. value是否在List中:in 和 not in

db.collection.find( { "field" : { $in : array } } );
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});

3. 判断元素是否存在 $exists

$exists用来判断一个元素(field)是否存在:

db.things.find( { a : { $exists : true } } ); 
db.things.find( { a : { $exists : false } } ); 

4. select distinct的实现:

  • 键值去重 类似于mysql中的 select distinct userId from consumerecords

    db.consumerecords.distinct("userId"):
    
  • 过滤之后去重, 类似于mysql中的select distinct userId from consumerecords where act="charge"

    db.consumerecords.distinct("userId",{act:"charge"}):
    
  • 去重之后求记录数, 类似于mysql中的 select count(distinct userId) from consumerecords

    db.consumerecords.distinct("userId").length:
    

5. 查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } );

注意用法是author.name

db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

db.blog.findOne({"author.name" : "Jane"})

如果不用点,那就需要用下面这句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

6. 数组大小匹配 $size

$size是匹配数组内的元素数量的,如有一个对象:{a:[“foo”]},他只有一个元素:

下面的语句就可以匹配:

db.things.find( { a : { $size: 1 } } );

7. 全部匹配 $all

a l l 和 all和 allin类似,但是他需要匹配条件内所有的值:

如有一个对象:

{ a: [ 1, 2, 3 ] }
下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );
但是下面这个条件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );

8. 正则表达式

mongo支持正则表达式,如:

// 后面的i的意思是区分大小写
db.customers.find( { name : /acme.*corp/i } ); 

9. group的实现

  • 分组求和:类似于mysql中的select act,sum(count) from consumerecords group by act

    db.consumerecords.group(
        {
        key:{act:true}, 
        initial:{ct:0},    
        $reduce:function(doc,prev)  
            {
            prev.ct = prev.ct + doc.count    
            }
        }
    )
    
    
  • 分组求和,过滤,类似mysql中的select act,sum(count) from consumerecords group by act having act="charge"

    db.consumerecords.group(
    {
        key:{act:true}, 
        initial:{ct:0},    
        $reduce:function(doc,prev)  
            {
            prev.ct = prev.ct + doc.count    
            },
        condition:{act:"charge"}
    }
    )
    

10. forEach

举例:可以用于复制collection

db.test(复制源表).find().forEach(function(x){
    db.target(目的表).insert(x);
})

11. 索引

单字段索引 (Single Field Index)
    db.person.createIndex( {age: 1} ) 

上述语句针对age创建了单字段索引,其能加速对age字段的各种查询请求,是最常见的索引形式,MongoDB默认创建的id索引也是这种类型。

{age: 1} 代表升序索引,也可以通过{age: -1}来指定降序索引,对于单字段索引,升序/降序效果是一样的。

复合索引 (Compound Index)

复合索引是Single Field Index的升级版本,它针对多个字段联合创建索引,先按第一个字段排序,第一个字段相同的文档按第二个字段排序,依次类推,如下针对age, name这2个字段创建一个复合索引。

    db.person.createIndex( {age: 1, name: 1} ) 
多key索引 (Multikey Index)

当索引的字段为数组时,创建出的索引称为多key索引,多key索引会为数组的每个元素建立一条索引,比如person表加入一个habbit字段(数组)用于描述兴趣爱好,需要查询有相同兴趣爱好的人就可以利用habbit字段的多key索引。

{"name" : "jack", "age" : 19, habbit: ["football, runnning"]}
db.person.createIndex( {habbit: 1} )  // 自动创建多key索引
db.person.find( {habbit: "football"} )
查询索引
mongo-9552:PRIMARY> db.person.getIndexes() // 查询集合的索引信息
[
    {
        "ns" : "test.person",  // 集合名
        "v" : 1,               // 索引版本
        "key" : {              // 索引的字段及排序方向
            "_id" : 1           // 根据_id字段升序索引
        },
        "name" : "_id_"        // 索引的名称
    }
]

Ref

  1. momgo agg 操作http://www.runoob.com/mongodb/mongodb-aggregate.html
  2. https://www.cnblogs.com/zhouxuchen/p/5136446.html
  3. https://docs.mongodb.com/manual/aggregation/
  4. https://yq.aliyun.com/articles/33726
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值