MongoDB 聚合中的條件 $first 忽略 NULL?


你可以在 aggregate() 下使用 $match 運算子來獲取第一條記錄。讓我們先建立一個包含文件的集合 -

> db.conditionalFirstDemo.insertOne({_id:100,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 100 }
> db.conditionalFirstDemo.insertOne({_id:101,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalFirstDemo.insertOne({_id:102,"StudentName":"Chris","StudentSubject":"MongoDB"});
{ "acknowledged" : true, "insertedId" : 102 }
>db.conditionalFirstDemo.insertOne({_id:103,"StudentName":"Chris","StudentSubject":"MongoDB"});
{ "acknowledged" : true, "insertedId" : 103 }
> db.conditionalFirstDemo.insertOne({_id:104,"StudentName":"Chris","StudentSubject":null});
{ "acknowledged" : true, "insertedId" : 104 }

以下是使用 find() 方法顯示某個集合中的所有文件的查詢 -

> db.conditionalFirstDemo.find();

這將產生以下輸出 -

{ "_id" : 100, "StudentName" : "Chris", "StudentSubject" : null }
{ "_id" : 101, "StudentName" : "Chris", "StudentSubject" : null }
{ "_id" : 102, "StudentName" : "Chris", "StudentSubject" : "MongoDB" }
{ "_id" : 103, "StudentName" : "Chris", "StudentSubject" : "MongoDB" }
{ "_id" : 104, "StudentName" : "Chris", "StudentSubject" : null }

以下是 MongoDB 聚合中的條件 $first 的查詢 -

> db.conditionalFirstDemo.aggregate([ { "$match": { "StudentSubject": { "$ne": null } } }, { "$group": { "_id": "$StudentName", "StudentSubject": { "$first": "$StudentSubject" } }} ]);

這將產生以下輸出 -

{ "_id" : "Chris", "StudentSubject" : "MongoDB" }

更新於: 2019 年 7 月 30 日

454 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告