如何从MongoDB数组中获取特定元素?
您可以使用聚合框架从MongoDB数组中获取特定元素。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.getParticularElement.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","C","C++","MongoDB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7ee027559dd2396bcfbfb1") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.getParticularElement.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "InstructorName" : "Larry", "InstructorTechnicalSubject" : [ "Java", "C", "C++", "MongoDB", "MySQL", "SQL Server" ] }
这是从数组中获取特定元素的查询-
> db.getParticularElement.aggregate([ ... { ... $project: ... { ... ElementFromAnArray: 1, ... FourthElement: { $arrayElemAt: [ "$InstructorTechnicalSubject", 3] }, ... ... } ... } ... ]);
以下是输出-
{ "_id" : ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement" : "MongoDB" }