我正在尝试对 MongoDB“$or”查询进行一些概要分析,但在 Mongo shell 中使用“explain()”命令时遇到了问题。当我使用 find 命令运行查询时,它可以正常工作并按预期返回一条记录。但是,当我在 find() 的末尾添加一个“explain()”时,出现以下错误:
uncaught exception: error: { "$err" : "invalid operator: $or", "code" : 10068 }
我正在尝试以下查询:
db.people.find({"query" :
{"$or" : [
{"site" : "mysite", "site_id" : "587125722"},
{"user_id" : ObjectId("4fb811aae4b0b628b485a58d")}
]},
"$orderby" : { "global_id" : 1, "user_id" : 1}
})
如果我将“$or”更改为“or”,explain() 工作正常,但查询返回 0 个结果。我的印象是它们的语法在有或没有 explain() 的情况下应该是相同的,所以我做错了什么?我正在使用 2.0.4 版。感谢任何可能提供帮助的人。
最佳答案
关键字“query”在内部用于打包“query”(请求服务器进行搜索)的“query”(指定要搜索的内容)部分,以使其在 BSON 文档中保持独特发送到服务器,但 shell 帮助程序(例如 .explain)强制此“打包”发生在您指定的任何内容上。通过将其包装在“查询”本身中,您将丢失所需的查询(您直接在其中使用“查询”)。
Matt 的回答通过解包您预先包装的请求避免了这种情况,这是执行此操作的正常方法......只需将“.explain()”添加到 Matt 重写的末尾,它应该会按您预期的方式工作。
如果您想保留您的格式,您只需将“$explain : true”添加到您的文档中,就像您使用“$orderby”而不是“.sort”一样。
db.people.find({"query" :
{"$or" : [
{"site" : "mysite", "site_id" : "587125722"},
{"user_id" : ObjectId("4fb811aae4b0b628b485a58d")}
]},
"$orderby" : { "global_id" : 1, "user_id" : 1},
"$explain" : true
})
查看 shell 助手“.explain”的 JavaScript 代码,了解它的作用:
> db.foo.find().explain
function (verbose) {
var n = this.clone();
n._ensureSpecial();
n._query.$explain = true;
n._limit = Math.abs(n._limit) * -1;
var e = n.next();
function cleanup(obj) {
if (typeof obj != "object") {
return;
}
delete obj.allPlans;
delete obj.oldPlan;
if (typeof obj.length == "number") {
for (var i = 0; i < obj.length; i++) {
cleanup(obj[i]);
}
}
if (obj.shards) {
for (var key in obj.shards) {
cleanup(obj.shards[key]);
}
}
if (obj.clauses) {
cleanup(obj.clauses);
}
}
if (!verbose) {
cleanup(e);
}
return e;
}
> db.foo.find()._ensureSpecial
function () {
if (this._special) {
return;
}
var n = {query:this._query};
this._query = n;
this._special = true;
}
>
关于MongoDB 外壳 : Error with "$or" query and explain(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11640432/