2017-10-08 28 views
2

我有此集合如何通過mongodb中的兩個鍵刪除重複項?

enter image description here

我將根據X和Y刪除重複數據時它們是相同的值,因此在這種情況下(需要刪除在z = 3和Z = 4)

我使用

db.collection.aggregate([{"$sort":{ "_id": 1 }},{"$group":{"_id":"$x","doc":{"$first":"$$ROOT"}}},{"$replaceRoot":{"newRoot":"$doc"}},{"$out":"collection"}]) 

,但有一個關鍵的X

Json View 

{ 
    "_id" : ObjectId("59d9e7b4ad433ce84a235e93"), 
    "x" : NumberInt(1), 
    "y" : NumberInt(1), 
    "z" : NumberInt(1) 
} 
{ 
    "_id" : ObjectId("59d9e7d0ad433ce84a235e95"), 
    "x" : NumberInt(1), 
    "z" : NumberInt(2), 
    "y" : NumberInt(2) 
} 
{ 
    "_id" : ObjectId("59d9e7d2ad433ce84a235e97"), 
    "z" : NumberInt(3), 
    "x" : NumberInt(2), 
    "y" : NumberInt(3) 
} 
{ 
    "_id" : ObjectId("59d9e7d4ad433ce84a235e99"), 
    "z" : NumberInt(4), 
    "x" : NumberInt(2), 
    "y" : NumberInt(3) 
} 
{ 
    "_id" : ObjectId("59d9e7d7ad433ce84a235e9b"), 
    "x" : NumberInt(3), 
    "y" : NumberInt(4), 
    "z" : NumberInt(5) 
} 
使用
+0

刪除重複的請出示從蒙戈樣本JSON文檔。 – Astro

回答

2

您可以使用多個參數分組。試試這個代碼,這將有助於與多個鍵值

db.collection.aggregate([{ "$sort": { "_id": 1 } }, 
 
{ 
 
    "$group": { 
 
    "_id": { "x": "$x", "y": "$y" }, 
 
    "doc": { "$first": "$$ROOT" } 
 
    } 
 
}, 
 
{ "$replaceRoot": { "newRoot": "$doc" } }, 
 
{ "$out": "collection" }]);

+0

添加'allowDiskUse'=> true,修復內存問題 –