How to Avoid Duplicate Entries in MongoDb Meteor App -
how avoid duplicate entries in mongodb in meteor application.
on command: db.products.find({},{"template_name": 1},{unique : true})
{ "_id" : objectid("5555d0a16ce3b01bb759a771"), "template_name" : "b" } { "_id" : objectid("5555d0b46ce3b01bb759a772"), "template_name" : "a" } { "_id" : objectid("5555d0c86ce3b01bb759a773"), "template_name" : "c" } { "_id" : objectid("5555d0f86ce3b01bb759a774"), "template_name" : "c" } { "_id" : objectid("5555d1026ce3b01bb759a775"), "template_name" : "a" } { "_id" : objectid("5555d1086ce3b01bb759a776"), "template_name" : "b" } i want retrieve unique template names , show them on html page.
use aggregation framework pipeline stages consist of $group , $project operators respectively. $group operator step groups input documents given key , return distinct documents in result. $project operator reshapes each document in stream, such adding new fields or removing existing fields:
db.products.aggregate([ { "$group": { "_id": "$template_name" } }, { "$project": { "_id": 0, "template_name": "$_id" } } ]) result:
/* 0 */ { "result" : [ { "template_name" : "c" }, { "template_name" : "a" }, { "template_name" : "b" } ], "ok" : 1 } you use meteorhacks:aggregate package implement aggregation in meteor:
add app with
meteor add meteorhacks:aggregate then use .aggregate function below.
var products = new mongo.collection('products'); var pipeline = [ { "$group": { "_id": "$template_name" } }, { "$project": { "_id": 0, "template_name": "$_id" } } ]; var result = products.aggregate(pipeline); -- update --
an alternative doesn't use aggregation using underscore's methods return distinct field values collection's find method follows:
var distincttemplatenames = _.uniq(collection.find({}, { sort: {"template_name": 1}, fields: {"template_name": true} }).fetch().map(function(x) { return x.template_name; }), true) ;
this return array distinct product template names ["a", "b", "c"]
you can check out tutorials explain above approach in detail: get unique values collection in meteor , meteor – distinct mongodb query.
Comments
Post a Comment