您可以在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" }