如何在 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 } }
廣告