2

我在 MongoDb 中有一个数据集合,其形状为:

[{ "_id": "1",
  "Sq1" : 5, 
  "Sq1comment" : "In general you aaaaaa.", 
  "Sq2" : 8, 
  "S2comment" : null, 
  "Sq3" : 5, 
  "Sq3comment" : "A person bbbbb."
 },
 { "_id": "2",
   "Sq1" : 4, 
   "Sq1comment" : "In general you cc.", 
   "Sq2" : 8, 
   "S2comment" : "A story ff", 
   "Sq3" : 5, 
   "Sq3comment" : null
 }
]

我想提取“评论”字段,但只反映结果中不为空的字段。

我可以通过查询一个接一个地提取字段(Sq1comment;Sq2comment,Sq3comment)

db.collection.find({ "Sq1comment": { $not: { $type: 10 } })

其输出为:

[{ "_id": "1",
  "Sq1comment" : "In general you aaaaaa.", 
  "Sq3comment" : "A person bbbbb."
 }]

或者如果我做一个聚合 $project 'comment' 字段,所有的空值都在那里:

db.collection.aggregate([{$project: 
   { "Sq1comment": "$Sq1comment",
     "Sq2comment": "$Sq2comment",
     "Sq3comment": "$Sq3comment"
   } }])

其输出为:

[{ "_id": "1",
  "Sq1comment" : "In general you aaaaaa.", 
  "S2comment" : null, 
  "Sq3comment" : "A person bbbbb."
 },
 { "_id": "2",
   "Sq1comment" : "In general you cc.", 
   "S2comment" : "A story ff", 
   "Sq3comment" : null
 }
]

我想要一个项目的数据来显示所有评论字段,但只有不为空的条目。因此排除空字段是聚合。

4

1 回答 1

0

也许你可以尝试$unwind,然后$group得到你想要的结果。

像这样:

{
  $unwind:
    {
      path: <field path>,
      includeArrayIndex: <string>,
      preserveNullAndEmptyArrays: <boolean>
    }
}

preserveNullAndEmptyArrays将有助于排除空值。

更多访问链接:

https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

https://docs.mongodb.com/manual/reference/operator/aggregation/group/

于 2019-07-16T10:01:04.587 回答