将$unwind运算符与$project一起使用,以获取数组中的第一个元素。让我们创建包含文档的集合。以下是查询
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"John","StudentSubject":["MongoDB","Python","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c41292d6669774125244e") } >db.getFirstElementInArrayDemo.insertOne({"StudentName":"Chris","StudentSubject":["Java","C"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c413f2d6669774125244f") } >db.getFirstElementInArrayDemo.insertOne({"StudentName":"Robert","StudentSubject":["C++","Ruby"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c9c41532d66697741252450") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.getFirstElementInArrayDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9c41292d6669774125244e"), "StudentName" : "John", "StudentSubject" : [ "MongoDB", "Python", "MySQL" ] } { "_id" : ObjectId("5c9c413f2d6669774125244f"), "StudentName" : "Chris", "StudentSubject" : [ "Java", "C" ] } { "_id" : ObjectId("5c9c41532d66697741252450"), "StudentName" : "Robert", "StudentSubject" : [ "C++", "Ruby" ] }
以下是获取数组中的第一个元素并使用聚合返回的查询
> db.getFirstElementInArrayDemo.aggregate([ ... {$unwind:"$StudentSubject"}, ... {$group:{"_id":"$_id","FirstElement":{$first:"$StudentSubject"}}}, ... {$project:{"_id":0,"FirstElement":1}} ... ]);
这将产生以下输出
{ "FirstElement" : "Java" } { "FirstElement" : "C++" } { "FirstElement" : "MongoDB" }
您可以使用$slice运算符find()
来获取数组中的第一个元素。以下是查询
> db.getFirstElementInArrayDemo.find({},{"StudentSubject":{$slice:1}});
这将产生以下输出
{ "_id" : ObjectId("5c9c41292d6669774125244e"), "StudentName" : "John", "StudentSubject" : [ "MongoDB" ] } { "_id" : ObjectId("5c9c413f2d6669774125244f"), "StudentName" : "Chris", "StudentSubject" : [ "Java" ] } { "_id" : ObjectId("5c9c41532d66697741252450"), "StudentName" : "Robert", "StudentSubject" : [ "C++" ] }