Return null default value if no result found

2020-02-15 04:22发布

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"
}

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

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

The result is:

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

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 }

How would I do this?

2条回答
冷血范
2楼-- · 2020-02-15 05:02

Why you dont check in callback if result==null and create your own empty object?

let name = "form4";
db.myCollec.find({"name":name} , {"name":1, "type":1, "_id":0}, function(err, result){
    if(err) {
         // Error handling
         return;
    }
    if (result==null){
        result = {"name":name, "type":null};
    }
});
查看更多
冷血范
3楼-- · 2020-02-15 05:06

You can use below aggregation

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

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

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]
    }
  }}
])
查看更多
登录 后发表回答