mongo常用的查询、聚合查询、更新文档

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43886133/article/details/94752684

文档数据

{
    "_id" : ObjectId("5ce16d20282ad14398151c5d"),
    "title" : "青海银监局行政处罚信息公开2015年第3号",
    "ctime" : 1449417600,
    "branch" : "青海银监局",
    "fp_id" : "9cafbadf4401d0bb5caab40f21bd064924289347",
    "url" : "http://www.cbrc.gov.cn/chinese/home/docView/18101EA3B11F4FE7AE2AB22A00E14A16.html",
    "web_contents" : [],
    "accessory" : [],
    "gtime" : 1558277408,
    "breadcrumb" : [
        "中国银行业监督管理委员会",
        "青海监管局",
        "政府信息公开",
        "公开目录",
        "行政处罚"
    ],
    "branch_tree" : {
        "0" : "中国银行业监督管理委员会",
        "1" : "政府信息公开",
        "2" : "青海银监局"
    },
    "article_info" : {
        "发布时间" : "2015-12-07",
        "文章来源" : "青海",
        "文章类型" : "原创"
    },
    "spider_name" : "fsp_cbrc", 
    "channel" : "行政处罚",
    "webname" : "中国银行业监督管理委员会",
    "domain" : "cbrc.gov.cn",
    "department" : "中国银行业监督管理委员会",
    "uid" : "d57eb94f97133e48adc3787fd3961d21",
    "path" : "fsp/fsp_cbrc"
}

聚合查询

  • 按照 branch_tree 的第“1”个元素, 及 gtime 分组 统计
db.fsp_department_raw22.aggregate([{"$group": {"_id": {"branch1":"$branch_tree.1","gtime":"$gtime"}, "count": {"$sum": 1}}},
    {"$project": {"_id": 0, "branch1": "$_id", "count": 1}},
    {"$sort": {"count": -1}}])
  • 查询 branch_tree 的第“1”个元素 为 政府信息公开的文档
db.getCollection('fsp_department_raw3').find({"branch_tree.1": "政府信息公开"})
  • 如果字段是字典, 查询内容时使用 <字段名.key>
db.getCollection('fsp_department_raw3').find({"branch_tree.1": "政府信息公开"})
  • 如果字段是列表, 查询内容时使用 <字段名.索引>
db.getCollection('fsp_department_raw3').find({"breadcrumb.3": "公开目录"})

更新文档

db.yjh1.find().forEach(function(item){                 
   db.yjh1.update({"_id":item._id, "branch_tree.1": "政府信息公开"},
          {"$set": {"branch_tree.1":item.branch}},false,true)
})


$match 筛选条件

[{"$match": {"gtime": {"$gt": lgtime, "$lt": now_time}}},
            {"$group": {"_id": {"department": "$department", "group_key": "$group_key", "stime": "$stime"},
                        "count": {"$sum": 1}}},
            {"$project": {"_id": 0, "group": "$_id", "count": 1}},
            {"$sort": {"count": -1}}]

查询某字段是否存在

  • 存在
db.getCollection('fsp_department_circ_raw').find({"department":"中国保险监督管理委员会","branch_tree.2":{"$exists":true}})
  • 不存在
db.getCollection('fsp_department_circ_raw').find({"department":"中国保险监督管理委员会","branch_tree.2":{"$exists":false}})
  • 删除指定字段
db.getCollection('fsp_department_raw').update({"department":"中国保险监督管理委员会","branch_tree.2":{"$exists":true}},{"$unset":{"branch_tree.2":1}},{multi:true})
  • 更新指定字段
db.getCollection('fsp_department_raw').update({"uid" : "fd8bcaf379b139d7ba43cd62d0ecb6eb"},{"$set":{"branch_tree":branch_tree}})

猜你喜欢

转载自blog.csdn.net/weixin_43886133/article/details/94752684