Pymongo 自动对输入字典进行排序
我正在使用 Pymongo 访问 Mongo 数据库。我想搜索指定位置附近名称包含字符串的所有人员。例如,我想搜索附近[105.0133, 21.3434]并且名称包含“Mark”的所有人。所以我这样写查询:(
db.users.find({ "location.coords": { "$nearSphere": [105.0133, 21.3434], "$maxDistance": 10/EARTH_RADIUS }, "name": "/Mark/" })
我的“users”集合中有一个索引“location.coords”)
该查询在 Mongodb 控制台中工作正常,但是在由 Pymongo 执行时,字典会像这样重新排序
{ "name": "/Mark/", "location.coords": { "$nearSphere": [105.0133, 21.3434], "$maxDistance": 10/EARTH_RADIUS } }
:( “name”键在“location.coords”之前,这不是我所期望的 - 也是 Mongodb 所期望的)
这导致 Mongodb 无法理解查询并且不返回任何结果。谁能帮我弄清楚如何强制 Pymongo 不重新排序我的字典。
感谢和问候
I am using Pymongo to access Mongo db. I want to search for all people nearby a specified location with name contains a string. For example, I want to search all people nearby [105.0133, 21.3434] and name contains 'Mark'. So I write the query like this:
db.users.find({ "location.coords": { "$nearSphere": [105.0133, 21.3434], "$maxDistance": 10/EARTH_RADIUS }, "name": "/Mark/" })
(I have an index "location.coords" in my "users" collection)
The query works fine in Mongodb console, but while execute by Pymongo, the dictionary being re-sort like this:
{ "name": "/Mark/", "location.coords": { "$nearSphere": [105.0133, 21.3434], "$maxDistance": 10/EARTH_RADIUS } }
(The "name" key is before "location.coords", that is not what I expected - also Mongodb expected)
That causes Mongodb cannot understand the query and returns no results. Can anyone help me to figure out how to force the Pymongo does not re-sort my dictionary.
Thanks and regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字典类型本质上是无序的。来自 python 文档:
如果您想按特定顺序索引字典,则必须以某种方式存储您的顺序。一种简单的方法是将密钥保存在列表中,例如:
您可能还想要 调查:
不幸的是,如果您需要更多帮助,则需要提供有关您情况的更多详细信息。
The dictionary type is inherently orderless. From the python documentation:
If you want to index your dictionary in a specific order, you'll have to store your order somehow. One easy way to do this is to keep your keys in a list, like:
You also might want to investigate:
Unfortunately if you need more help than that, you'll need to provide more details of your situation.
问题不在于顺序,而在于
“/Mark/”
。带有正斜杠的表示法是 javascript shell 提供的一种便利,并且不构成正则表达式模式本身的一部分(除非您希望它们是文字斜杠,在这种情况下我误解了您的问题)。要在 PyMongo 中使用正则表达式(“包含”)过滤器,您需要传递 Python 正则表达式对象。试试这个:
The issue isn't the ordering, it's
"/Mark/"
. The notation with forward slashes is a convenience provided by the javascript shell, and don't constitute a part of the regular expression pattern itself (unless you meant for them to be literal slashes, in which case I've misunderstood your question).To use a regular expression ("contains") filter in PyMongo, you need to pass a Python regular expression object. Try this: