您可以在聚合框架的帮助下使用多个键执行不同的操作。
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f74488d10a061296a3c53") } > db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f744b8d10a061296a3c54") } > db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f74598d10a061296a3c55") } > db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f745e8d10a061296a3c56") } > db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Carol","StudentAge":27,"StudentMathMarks":54}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f74688d10a061296a3c57") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.distinctWithMultipleKeysDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c7f74488d10a061296a3c53"), "StudentName" : "Mike", "StudentAge" : 22, "StudentMathMarks" : 56 } { "_id" : ObjectId("5c7f744b8d10a061296a3c54"), "StudentName" : "Mike", "StudentAge" : 22, "StudentMathMarks" : 56 } { "_id" : ObjectId("5c7f74598d10a061296a3c55"), "StudentName" : "Bob", "StudentAge" : 23, "StudentMathMarks" : 45 } { "_id" : ObjectId("5c7f745e8d10a061296a3c56"), "StudentName" : "Bob", "StudentAge" : 23, "StudentMathMarks" : 45 } { "_id" : ObjectId("5c7f74688d10a061296a3c57"), "StudentName" : "Carol", "StudentAge" : 27, "StudentMathMarks" : 54 }
这是使用多个键执行不同查询的查询-
> c = db.distinctWithMultipleKeysDemo; test.distinctWithMultipleKeysDemo > myResult = c.aggregate( [ {"$group": { "_id": { StudentName:"$StudentName", StudentAge: "$StudentAge" } } } ] );
以下是输出-
{ "_id" : { "StudentName" : "Carol", "StudentAge" : 27 } } { "_id" : { "StudentName" : "Bob", "StudentAge" : 23 } } { "_id" : { "StudentName" : "Mike", "StudentAge" : 22 } }