0
我想检查嵌套字段是否存在或为空。如果存在,则返回该值,否则返回该字段的默认值。需要使用.aggregate
,因为我还需要执行一些集合操作。
说我的文档是这样的:
{
"_id" : ObjectId("581a18d41b6c5c752f11c87a"),
"email": "[email protected]",
"name" : "xxxxxx",
"memberType" : "Guest",
"name" : "M1",
"inviter": {
"status": 'active'
}
},
{
"_id" : ObjectId("581a18d41b6c5c752f11c87b"),
//....
"name" : "M2",
"inviter": {
}
}
,我想获得像
{
"_id" : ObjectId("581a18d41b6c5c752f11c87a"),
"data": ["M1","active"]
},
{
"_id" : ObjectId("581a18d41b6c5c752f11c87b"),
"data": ["M2","inactive"]
}
我试过数据:
db.getCollection('users').aggregate([
{$match:{"email" :{$ne:'[email protected]'}}},
{$sort:{_id:1}},
{$project:{
"_id" : "$_id",
"data":
["$name",
{ "$inviter.status":{$ifNull: [ "$inviter.status", 'inactive'] }},
]
}}
])
,但得到的错误
“ERRMSG”:“无效的操作 ‘$ inviter.status’”,
是可以使用支票嵌套$ifNull
场或我怎么能解决呢?
项目基本上是指定字段列入。你以fieldname:$ literal的形式给它。在你的例子中,它应该是{“status”:{$ ifNull:[“$ inviter.status”,'inactive']}}, – user1211