为此,请aggregate()
在MongoDB中使用。在那,使用$slice在array内对array进行切片。让我们创建一个包含文档的集合-
> db.demo111.insertOne( ... { ... "_id" : 101, ... "Name" : "Chris", ... "Details" : [ ... { ... "_id" : 101, ... "Score" : 78, ... "Subjects" : [ ... { ... "_id" : "10001", ... "SubjectName" : "MySQL" ... }, ... { ... "_id" : "10003", ... "SubjectName" : "MongoDB" ... } ... ] ... }, ... { ... "_id" : 102, ... "Score" : 87, ... "Subjects" : [ ... { ... "_id" : "10004", ... "SubjectName" : "Java" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo111.find();
这将产生以下输出-
{ "_id" : 101, "Name" : "Chris", "Details" : [ { "_id" : 101, "Score" : 78, "Subjects" : [ { "_id" : "10001", "SubjectName" : "MySQL" }, { "_id" : "10003", "SubjectName" : "MongoDB" } ] }, { "_id" : 102, "Score" : 87, "Subjects" : [ { "_id" : "10004", "SubjectName" : "Java" } ] } ] }
以下是在数组内部切片数组的查询-
> db.demo111.aggregate([ ... { "$addFields": { ... "Details": { ... "$map": { ... "input": "$Details", ... "as": "out", ... "in": { ... "_id": "$$out._id", ... "Score": "$$out.Score", ... "Subjects": { "$slice": [ "$$out.Subjects", 1 ] } ... } ... } ... } ... }} ... ])
这将产生以下输出-
{ "_id" : 101, "Name" : "Chris", "Details" : [ { "_id" : 101, "Score" : 78, "Subjects" : [ { "_id" : "10001", "SubjectName" : "MySQL" } ] }, { "_id" : 102, "Score" : 87, "Subjects" : [ { "_id" : "10004", "SubjectName" : "Java" } ] } ] }