如何在 MongoDB 中使用多重 key 高效执行“distinct”操作?
你可以借助聚合框架执行多重 key 的 distinct 操作。
为了理解这个概念,让我们创建一个带有文档的集合。创建带有文档的集合的查询如下 −
> 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()` 方法从集合中显示所有文档。查询如下 −
> 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 }
以下是执行多重 key distinct 操作的查询 −
> 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 } }
广告