要获得一对不同的对象,请使用$组。让我们创建一个包含文档的集合-
> db.demo522.insertOne({"Name":"John","Score":45});{ "acknowledged" : true, "insertedId" : ObjectId("5e89b646b3fbf26334ef611b") } > db.demo522.insertOne({"Name":"Bob","Score":67});{ "acknowledged" : true, "insertedId" : ObjectId("5e89b64eb3fbf26334ef611c") } > db.demo522.insertOne({"Name":"John","Score":55});{ "acknowledged" : true, "insertedId" : ObjectId("5e89b655b3fbf26334ef611d") } > db.demo522.insertOne({"Name":"Bob","Score":33});{ "acknowledged" : true, "insertedId" : ObjectId("5e89b65cb3fbf26334ef611e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo522.find();
这将产生以下输出-
{ "_id" : ObjectId("5e89b646b3fbf26334ef611b"), "Name" : "John", "Score" : 45 } { "_id" : ObjectId("5e89b64eb3fbf26334ef611c"), "Name" : "Bob", "Score" : 67 } { "_id" : ObjectId("5e89b655b3fbf26334ef611d"), "Name" : "John", "Score" : 55 } { "_id" : ObjectId("5e89b65cb3fbf26334ef611e"), "Name" : "Bob", "Score" : 33 }
以下是查询以获取MongoDB中所有子文档的一对不同的对象-
> var query = [ ... { ... "$group": { ... "_id": "$Name", ... "Score": { "$sum": "$Score" } ... } ... }, ... { ... "$project": { ... "Name": "$_id", "_id": 0, "Score": 1 ... } ... } ... ]; > > db.demo522.aggregate(query);
这将产生以下输出-
{ "Score" : 100, "Name" : "Bob" } { "Score" : 100, "Name" : "John" }