MongoDB内嵌文档查询

MongoDB内嵌文档查询

  1. 示例数据结构
 [{"name": "lisa", "age": 17,
              "friends": [{"name": "tom", "tel": "17876353434"}, {"name": "bob", "tel": "17876753434"}]},
             {"name": "anna", "age": 17,
              "friends": [{"name": "tony", "tel": "17876358434"}, {"name": "ming", "tel": "17876753434"}]}]

在这里插入图片描述
在这里插入图片描述

  1. 查询
    一般在查询时,只针对内嵌文档的特定键值去查询,可以使用"."来表示进入内嵌文档。

查询friends中name为tom的信息:

query_dict = {"friends.name": "tom"}
result=mycol.find_one(query_dict)

结果如下:
{’_id’: ObjectId(‘6099fe790abc10d0ffd5532b’), ‘name’: ‘lisa’, ‘age’: 17, ‘friends’: [{‘name’: ‘tom’, ‘tel’: ‘17876353434’}, {‘name’: ‘bob’, ‘tel’: ‘17876753434’}]}

  1. 取消查询结果中的"_id"列
query_dict = {"friends.name": "tom"}
result=mycol.find_one(query_dict, {"_id": 0})

结果如下:
{‘name’: ‘lisa’, ‘age’: 17, ‘friends’: [{‘name’: ‘tom’, ‘tel’: ‘17876353434’}, {‘name’: ‘bob’, ‘tel’: ‘17876753434’}]}
另,如果想取消查询friends里的tel列,则代码如下:

query_dict = {"friends.name": "tom"}
result=mycol.find_one(query_dict, {"friends.tel": 0})

4.完整实例代码如下(python)

import pymongo

myclient = pymongo.MongoClient("mongodb://这里记得改地址噢/")
mydb = myclient["test_db"]  # 数据库
mycol = mydb["test_col"]  # 集合

test_data = [{"name": "lisa", "age": 17,
              "friends": [{"name": "tom", "tel": "17876353434"}, {"name": "bob", "tel": "17876753434"}]},
             {"name": "anna", "age": 17,
              "friends": [{"name": "tony", "tel": "17876358434"}, {"name": "ming", "tel": "17876753434"}]}]

# mycol.insert_many(test_data)  # 将test_data存入集合中

query_dict = {"friends.name": "tom"}
result1=mycol.find_one(query_dict, {"friends.tel": 0})
result2=mycol.find_one(query_dict, {"_id":0,"friends.tel": 0})
print(result2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值