how to find duplicate field in subdocument array in MongoDB -
i'm trying find way find , remove duplicate object same field in subdocument array.
basically collection has schema.
[{ "_id": objectid("578953db976cea724bbdbb60"), "units": [{ "description": "a1" }, { "description": "b1" }, { "description": "a1" }, { "description": "c1" }] }, { "_id": objectid("578953db976cea724bbdbb61"), "units": [{ "description": "a2" }, { "description": "b2" }, { "description": "a2" }, { "description": "c2" }] }]
i wish find , remove duplicate field same description.
so first, need identify "a1" , a2" respectively.
thanks.
update (output should be):
[{ "_id": objectid("578953db976cea724bbdbb60"), "units": [{ "description": "a1" }, { "description": "b1" }, { "description": "c1" }] }, { "_id": objectid("578953db976cea724bbdbb61"), "units": [{ "description": "a2" }, { "description": "b2" }, { "description": "c2" }] }]
use javascript
db.collection.find().foreach(function(element){ var descriptions = element.units.map(function(unit){return unit.description;}) element.units = element.units.filter(function(value, index, array){ return descriptions.indexof(value) == index; }) db.save(element); })
Comments
Post a Comment