如果未找到结果,则返回 null 默认值

编程入门 行业动态 更新时间:2024-10-28 10:29:26
本文介绍了如果未找到结果,则返回 null 默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个看起来像这样的集合:

I have a collection that looks like this:

{ "value" : "20", "type" : "square", "name" : "form1" } { "value" : "24", "type" : "circle", "name" : "form2" } { "value" : "12", "type" : "square", "name" : "form3" }

我想提取一个 name = form2 的文档,所以我输入:

I want to extract a document with name = form2 so I type:

db.myCollec.find({"name":"form2"} , {"name":1, "type":1, "_id":0})

结果是:

{ "name" : "form2", "type" : "circle" }

现在如果我想找到一个带有 name = form4 的文档,我输入:

Now if I want to find a document with name = form4 I type:

db.myCollec.find({"name":"form4"} , {"name":1, "type":1, "_id":0})

但这不会返回任何内容,因为没有具有此名称的文档.

But this returns nothing because there is no document with this name.

但是我希望返回值看起来像这样:

However I want the return value to look like this:

{ "name" : "form4", "type" : null }

我该怎么做?

推荐答案

可以使用下面的聚合

如果没有 ,Mongodb 不会产生结果$match通过查询找到的数据.

Mongodb doesn't produce the result if there is not $matched data found with the query.

但是你可以使用$facet 聚合在单个阶段内处理多个聚合管道.

But you can use $facet aggregation which processes multiple aggregation pipeline within single stage.

所以首先使用 $facet 获取$matched 文档并使用 $projection 如果没有 ($ifNull) 数据找到.

So first use $facet to get the $matched documents and use $projection if no ($ifNull) data found.

let searchTerm = "form2" db.myCollec.aggregate([ { "$facet": { "data": [ { "$match": { "name": searchTerm }}, { "$project": { "name": 1, "type": 1, "_id": 0 }} ] }}, { "$project": { "name": { "$ifNull": [{ "$arrayElemAt": ["$data.name", 0] }, searchTerm ] }, "type": { "$ifNull": [{ "$arrayElemAt": ["$data.type", 0] }, null] } }} ])

更多推荐

如果未找到结果,则返回 null 默认值

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

发布评论

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

>www.elefans.com

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