How to avoid duplicate entries in the MetoDroid app

How to avoid duplicate records in mongoDb in Meteor app.

In a team: 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 only want to get unique template names and show them in HTML page.

+3


source to share


2 answers


Use an aggregation framework where your pipeline stages consist of and operators respectively. The operational command groups the input documents by the given key and thus returns the result as a result. The operator converts each document to a stream, for example by adding new fields or removing existing fields: $group

$project

$group

$project

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
}

      

Then you can use meteorhacks: aggregate package to implement aggregation in Meteor:

Add to your application

meteor add meteorhacks:aggregate

      

Then just use as shown below. .aggregate



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 to use the underscore methods to return different field values ​​from the collection search 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 different product template names ["A", "B", "C"]

You can check out some tutorials that explain the above approach in detail: Get unique values ​​from collection in Meteor and METEOR - MONDOD DISCLAIMER .

+4


source


You can use distinct mongodb like:

db.collectionName.distinct("TEMPLATE_NAME")

      



This query will return you an array of different TEMPLATE_NAME

+4


source







All Articles