美文网首页我爱编程
mongodb-模糊查询+聚合函数+连表查询+排序

mongodb-模糊查询+聚合函数+连表查询+排序

作者: firststep | 来源:发表于2018-03-02 17:17 被阅读0次

    今天我们来聊一下nosql mongodb的模糊查询:

    在mysql中需要做模糊查询的时候一般都是用的关键字like,而mongodb中用的主要是$regex.
    1. mysql: select * from 表一 where name like ’%haha%’
    2. mongodb: db.表一.find({name:{$regex:/haha/}})
      那么在聚合函数中如何把上一个博客上讲的链表查询一起串起来呢?我们不废话直接上代码:
    db.getCollection('nelnmomclubwpcTransitionCouponRecord').aggregate([
             {$lookup: {
                        from: "表二",
                        localField: "openId",
                        foreignField: "socials.openId", 
                        as: "member" 
                        }
             },
        { 
            $project: { 'year_data': {$year: "$createdAt"},
                                'month_data': {$month: "$createdAt"},
                                'member' :1
                    }
            },
            {$unwind: "$member"},
            {
                $match: {
                    '$or' : [
                        {
                            'member.properties' : {
                                '$elemMatch': {'name': 'name', 'value': {$regex:"小"}}
                             }
                         }
                     ]
                }
            },
            {$sort: {"_id.year_data":-1, "_id.month_data":-1}}
    
    1. $unwind; 分割嵌入数组到自己顶层文件
    2. elemMatch: 嵌套查询(用于多个条件)
    3. $or 匹配多个键(满足一个即可)

    相关文章

      网友评论

        本文标题:mongodb-模糊查询+聚合函数+连表查询+排序

        本文链接:https://www.haomeiwen.com/subject/qynaxftx.html