对于背景,如果要比较两个字段,则不能使用以下语法(因为它与文字字符串"$ lastName"而不是$ lastName字段的内容进行比较):
For background, if I want to compare two fields, I can't use the following syntax (because it compares to the literal string "$lastName" rather than the contents of the $lastName field):
"$match": { "firstName": { $ne : "$lastName"} }我必须使用这个:
"$match": { "$expr": { $ne : [ "$firstName", "$lastName" ] } }如果要测试字段是否存在,必须使用第一种格式:
If I want to test that a field exists I must use the first format:
"$match": { "fullName": { "$exists": true } }我认为以后一种格式表示$ exists运算符的正确方法会引发错误:
What I think would be the correct way for expressing the $exists operator in the latter format throws an error:
db.docs.aggregate([ { "$match": { "$expr": { "$exists": [ "$fullName", true ] } } } ]) assert: command failed: { "ok" : 0, "errmsg" : "Unrecognized expression '$exists'", "code" : 168, "codeName" : "InvalidPipelineOperator" } : aggregate failed这是否意味着至少在某些情况下无法合并这些操作?具体来说,假设我想在任一 $ fullName $存在 OR $ firstName $ ne $ lastName的地方找到文档.可以表达出来吗?
Does this mean it is not possible to combine these operations, at least in some conditions? Specifically, suppose I want to find docs where either $fullName $exists OR $firstName $ne $lastName. Can that be expressed?
推荐答案您将需要使用$or逻辑运算符执行此操作.
You will need to use the $or logical operator to do this.
{ "$or": [ { "$expr": { "$ne": [ "$firstName", "$lastName" ] } }, { "fullName": { "$exists": true } } ] }您上次查询失败,因为mongod认为$exists是您正在传递$expr运算符的表达式.
You last query failed because mongod thinks $exists is the expression you are passing the the $expr operator.
更多推荐
在MongoDB表达式中使用$ exists
发布评论