MongoDB内嵌文档查询
- 示例数据结构
[{"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"}]}]
- 查询
一般在查询时,只针对内嵌文档的特定键值去查询,可以使用"."来表示进入内嵌文档。
查询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’}]}
- 取消查询结果中的"_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)