Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Avoid Duplicate Entries in MongoDb Meteor App

Tags:

mongodb

meteor

How to avoid duplicate entries in mongoDb in Meteor application.

On the 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 to retrieve only the unique template names and show them on HTML page.

like image 828
garima Avatar asked Jan 08 '23 09:01

garima


1 Answers

Use the aggregation framework where your pipeline stages consist of the $group and $project operators respectively. The $group operator step groups the input documents by the given key and thus will return distinct documents in the result. The $project operator then reshapes each document in the stream, such as by 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 could then use the meteorhacks:aggregate package to implement the aggregation in Meteor:

Add to your app with

meteor add meteorhacks:aggregate

Then simply use .aggregate function like 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 that doesn't use aggregation is using underscore's methods to return distinct field values from the collection's find method as follows:

var distinctTemplateNames = _.uniq(Collection.find({}, {
    sort: {"TEMPLATE_NAME": 1}, fields: {"TEMPLATE_NAME": true}
}).fetch().map(function(x) {
    return x.TEMPLATE_NAME;
}), true)

;

This will return an array with distinct product template names ["A", "B", "C"]

You can check out some tutorials which explain the above approach in detail: Get unique values from a collection in Meteor and METEOR – DISTINCT MONGODB QUERY.

like image 127
chridam Avatar answered Jan 17 '23 14:01

chridam