在MongoDB表达式中使用$ exists

编程入门 行业动态 更新时间:2024-10-12 16:26:53
本文介绍了在MongoDB表达式中使用$ exists的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于背景,如果要比较两个字段,则不能使用以下语法(因为它与文字字符串"$ 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

本文发布于:2023-11-22 01:31:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615451.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   MongoDB   exists

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!