我有一个看起来像这样的集合:
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 默认值
发布评论