哪有什么岁月静好,不过是有人替你负重前行!

mongo中的模糊查询

以下是一个mongo查询的综合应用,即介绍一个生产中实际应用的模糊查询,当然其实也很简单,主要用到mongo中的模糊查询和$or查询,以及并的关系,下面是一个mongo中的一条记录

{ 
    "_id" : "ffe6a068-9043-4334-97d2-75387340e655", 
    "file_id" : "ffe6a068-9043-4334-97d2-75387340e655", 
    "name" : "中国正大", 
    "update_time" : NumberInt(1554975642), 
    "create_time" : NumberInt(1554975642), 
    "content" : "中国正大相关信息", 
    "file_url" : "", 
    "file_type" : "", 
    "user_ids" : [
        1.0, 
        10.0
    ], 
    "group_ids" : [

    ], 
    "is_common" : NumberInt(0), 
    "confidence" : -1.0, 
    "obj_id" : "", 
    "source" : "", 
    "content_time" : "", 
    "author" : "", 
    "summary" : "", 
    "info_type" : "00", 
    "sub_info_type" : "", 
    "title" : "", 
    "word_num" : NumberInt(8)
}

对上面一条记录或者更多条记录我们生产中的需求是:查询出集合中(mongo中的集合即是mysql中的表),name或content中包含"正大"二字的记录(关键词即是用户随机输入的,其实是一个变量),并且时间戳的值大于某一个开始时间和某一个结束时间(这个也是用户在前端进行选择,然后我们拿到前端的请求来进行查询的),并且文件的类型即info_type字段的值为"00",“00”代表的是word也是前端用户选择后我们获取的条件之一,当然还有其他条件想进行尝试可以自由发挥

下面就是使用mongo语句进行实现的上面的需求:

db.getCollection("subscribe_test").find({$or:[{"name":{"$regex":"正大"}},{"content":{"$regex":"正大"}}],"update_time":{$gte:1,$lte:2000000000},info_type:"00"})

对于查询我们有的时候会选择在程序中进行,有的小伙伴会问上面的mongo语句怎么在编程语言中进行实现,下面是用python语言中进行实现的,我们会引用python中操作mongo的一个模块即pymongo模块可以使用pip install pymongo在控制台或cmd中进行一键安装,至于如何使用也很简单,可以自行百度或者访问我的另一篇博客:pymono的简单使用,下面附上用python代码实现上面需求的业务代码:

import pymongo
import re
# 创建数据库连接
client = pymongo.MongoClient(host='127.0.0.1', port=8014) #填写自己本机数据库的ip和port或者远程服务器数据库的ip和port
# 指定数据库db1,没有则创建数据库db1
db = client.dataretrieve
#指定数据库中指定的表
collection=db.subscribe_test

"""1、对表中的数据进行查询"""
"""
db.collection.find(query, projection)
query :可选,使用查询操作符指定查询条件
projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。
"""
query = {}
query["$or"] = [
    {"name": re.compile("正大")},
    {"content": re.compile("正大")},
]
query["file_type"] = "00"
query["update_time"] = {"$gte": 0,"$lte": 2000000000}
row=collection.find(filter=query)
for r in row:
    print(r["content"])

下面是生产中实际的开发代码,只供参考,只是把上面的一些常量,换成了从前端请求的数据:

def person_handler(req_params, page_size, search_offset):
    """
    去mongo中查询个人数据
    :param req_params:
    :param page_size:
    :param search_offset:
    :return:
    """
    results = []
    query = {}
    update_time = {}
    if 'start_time' in req_params and req_params["start_time"]:
        start_time = int(req_params["start_time"])
        update_time['$gte'] = start_time
    if 'end_time' in req_params and req_params['end_time']:
        end_time = int(req_params["end_time"])
        update_time['$lte'] = end_time
    if update_time:
        query["update_time"] = update_time
    if 'file_type' in req_params and req_params['file_type']:
        query["file_type"] = req_params["file_type"]
    if 'user_ids' in req_params and req_params['user_ids']:
        query['user_ids'] = int(req_params['user_id'])
    serch_keywords = req_params["search_keywords"]

    query["$or"] = [
        {"name": re.compile(serch_keywords)},
        {"content": re.compile(serch_keywords)},
    ]
    print(query)
    result = person_mongodao.search(filter=query).skip(search_offset).limit(page_size)
    count = person_mongodao.search(filter=query).skip(search_offset).limit(page_size).count()
    for row in result:
        results.append(row)
    additions = {"word_segs": req_params["search_keywords"], "remind": 0}
    print("查询结果", results)
    return results, additions, count

如果有小伙伴说我用的不是python语言譬如java用代码怎么实现呢?那么如果你会写mysql来实现上面的需求的话本博主可以推荐你使用mongo的一款可视化工具Studio 3T来将mysql语句转换成mongo语句,python语句,java语句等

mysql语句也类似mongo语句有一个控制台可以来进行书写mysql语句,然后进行查询之后将结果进行转换

以上就是关于mongo模糊查询的简单使用,希望对你有所帮助,原创不易,转载请说明出处,谢谢!!!!

 

posted @ 2019-04-12 11:27  迎风而来  阅读(33191)  评论(1编辑  收藏  举报
/*吸附球*/