如果未找到结果,则返回空默认值 [英] Return null default value if no result found

查看:212
本文介绍了如果未找到结果,则返回空默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 }

我该怎么做?

推荐答案

您可以在下面的聚合中使用

You can use below aggregation

如果没有 ,则Mongodb不会产生结果在查询中找到$match 数据.

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

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

因此,请先使用 $facet 获取> $match 文档并使用> $project ion(否)( $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]
    }
  }}
])

这篇关于如果未找到结果,则返回空默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆