对嵌入式mongodb文档的精确查询不起作用
根据mongodb文档中关于查询嵌入文档的说明,可以通过按存储顺序指定文档的所有字段来执行精确的查询 这似乎对我不起作用。即使我使用find_one检索文档,然后复制粘贴它,搜索也不会返回任何结果对嵌入式mongodb文档的精确查询不起作用,mongodb,pymongo,Mongodb,Pymongo,根据mongodb文档中关于查询嵌入文档的说明,可以通过按存储顺序指定文档的所有字段来执行精确的查询 这似乎对我不起作用。即使我使用find_one检索文档,然后复制粘贴它,搜索也不会返回任何结果 In [57]: TestColl.find_one({'data.local_dt': {'$exists': True}}) Out[57]: {u'_id': ObjectId('570ddba7f6858f77be9fb8ac'), u'data': {u'local_dt': {u'h
In [57]: TestColl.find_one({'data.local_dt': {'$exists': True}})
Out[57]:
{u'_id': ObjectId('570ddba7f6858f77be9fb8ac'),
u'data': {u'local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}}
In [58]: TestColl.find({'data.local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}).count()
Out[58]: 0
复制的全套步骤:
In [1]: from pymongo import MongoClient
In [2]: TestColl = MongoClient().Stage_database.TestColl
In [3]: TestColl.remove()
Out[3]: {u'n': 2, u'ok': 1}
In [4]: TestColl = MongoClient().Stage_database.TestColl
In [5]: doc = {'data': {'local_dt': {'year': 2016, 'month': 4, 'hour': 22}}}
In [6]: TestColl.insert(doc)
Out[6]: ObjectId('570ddfe7f6858f84169707fd')
In [7]: TestColl.find_one({'data.local_dt': {'$exists': True}})
Out[7]:
{u'_id': ObjectId('570ddfe7f6858f84169707fd'),
u'data': {u'local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}}
In [8]: TestColl.find({'data.local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}).count()
Out[8]: 0
In [9]: TestColl.find({'data.local_dt': {'hour': 22, 'month': 4, 'year': 2016}}).count()
Out[9]: 0
你应该使用。符号
我认为您在这里缺少的是,尽管python dict以特定顺序(按键名)显示键,但它们实际上并没有以这种方式存储在数据库中。如果您查看
mongo
shell,那么我认为这将得到证实。因此,实现这一点的“正确”方法是每个属性的“点符号”路径,而不是期望精确匹配。“点符号”形式的存在是非常合理和准确的,因此您可以测试“属性”上的值,而不仅仅是“精确对象”。我同意点符号是有效的。我的问题不是“如何搜索文档中的嵌入字段?”,而是“为什么精确查询不起作用?”如果它以任何合理的方式不起作用,那么为什么精确对象查询甚至存在?我知道这是有效的。我的目标不是找出如何查询子字段,而是理解为什么精确的查询不起作用。把它看作是一种智力练习!
In [1]: from pymongo import MongoClient
In [2]: TestColl = MongoClient().Stage_database.TestColl
In [3]: TestColl.remove()
Out[3]: {u'n': 2, u'ok': 1}
In [4]: TestColl = MongoClient().Stage_database.TestColl
In [5]: doc = {'data': {'local_dt': {'year': 2016, 'month': 4, 'hour': 22}}}
In [6]: TestColl.insert(doc)
Out[6]: ObjectId('570ddfe7f6858f84169707fd')
In [7]: TestColl.find_one({'data.local_dt': {'$exists': True}})
Out[7]:
{u'_id': ObjectId('570ddfe7f6858f84169707fd'),
u'data': {u'local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}}
In [8]: TestColl.find({'data.local_dt': {u'hour': 22, u'month': 4, u'year': 2016}}).count()
Out[8]: 0
In [9]: TestColl.find({'data.local_dt': {'hour': 22, 'month': 4, 'year': 2016}}).count()
Out[9]: 0
TestColl.find({'data.local_dt': {'hour': 22, 'month': 4, 'year': 2016}}).count()
TestColl.find({
"data.local_dt.hour": 22,
"data.local_dt.year": 2016,
"data.local_dt.month": 4
})
.count()