意外的 MongoDB“OR”查询行为
我正在测试 spring-data 并且它支持 mongodb。
我对使用 or 查询时的查询创建有疑问。考虑以下事项:
Query query = new Query().or(new Query(where("receiverId").is(userId)), new Query(where("requesterId").is(userId)));
query.and(where("status").is(status));
这将导致以下 mongodb 查询:
"$or" : [ { "receiverId" : { "$oid" : "4d78696025d0d46b42d9c579"}} , { "requesterId" : { "$oid" : "4d78696025d0d46b42d9c579"}}] , "status" : "REQUESTED"}
这将返回零结果,而预期结果为 1。在 mongodb 命令中运行此查询会导致以下错误:
error: { "$err" : "invalid operator: $oid", "code" : 10068 }
修改查询并在 mongodb 命令中运行它工作正常:
{ "$or" : [ { "receiverId" : ObjectId("4d78696025d0d46b42d9c579")} , { "requesterId" : ObjectId("4d78696025d0d46b42d9c579")}] , "status" : "REQUESTED"}
注意使用 ObjectId("...") 而不是 $oid。
我是否以错误的方式处理某事?也许查询设置错误?
I'm testing out spring-data and it's mongodb support.
I have a question about the query creation when using or-queries. Consider the following:
Query query = new Query().or(new Query(where("receiverId").is(userId)), new Query(where("requesterId").is(userId)));
query.and(where("status").is(status));
This will result in the following mongodb query:
"$or" : [ { "receiverId" : { "$oid" : "4d78696025d0d46b42d9c579"}} , { "requesterId" : { "$oid" : "4d78696025d0d46b42d9c579"}}] , "status" : "REQUESTED"}
This returns zero results while one is expected. Running this query in mongodb command results in following error:
error: { "$err" : "invalid operator: $oid", "code" : 10068 }
Modifying the query and running it in mongodb command works fine:
{ "$or" : [ { "receiverId" : ObjectId("4d78696025d0d46b42d9c579")} , { "requesterId" : ObjectId("4d78696025d0d46b42d9c579")}] , "status" : "REQUESTED"}
Notice the use of ObjectId("...") instead of $oid.
Am I going about something the wrong way? Maybe setting up the query wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在运行时检查该查询变量,或者您在 MongoDB 日志中看到了什么?
在 C# 驱动程序中,如果检查查询变量,您也会看到 $oid,但这不是发送到服务器的实际查询。在某些时候,它会将其更改为有效的 MongoDB 查询。
如果您在 Linux 上运行,您可能需要启动
mongosniff
,它会在发生时向您显示实时查询、更新和插入。如果您使用的是 Windows,则应使用-vvvv
标志启动mongod.exe
,这将使其能够将每个查询、更新、插入或命令记录到日志文件中。然后您实际上可以看到正在提交的确切查询。
Are you inspecting that query variable at runtime or is that what you are seeing in MongoDB's logs?
Int he C# driver, if you inspect the query variable, you see $oid as well, but that is not the actual query that is sent to the server. At some point, it changes that to a valid MongoDB query.
If you are running on linux, you may want to start up
mongosniff
which will show you realtime queries, updates and inserts as they happen. If you are on Windows, you should start upmongod.exe
with-vvvv
flag which will enable it to log every query, update, insert, or command to the log file.Then you can actually see the exact query that is being submitted.