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

查看:33
本文介绍了如果未找到结果,则返回 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 默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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