简体   繁体   中英

how to find the distinct values of a field in a MongoDB collection using Node MongoClient

In my MEAN application, I need to find the distinct values of a field named "DataFields" from my collection "Fixed_Asset_Register", using (non-mangoose) MongoClient:

var mongodb = require('mongodb');

var assert = require('assert');

var MongoClient = mongodb.MongoClient;

MongoClient.connect(url, function (err, db) {
    if (err) {
        console.log('Unable to connect to the mongoDB server. Error:', err);
    } else {
        console.log('Connection established to', url);

        var collection = db.collection('Fixed_Asset_Register');
        var distictDataFieldsValue = ?

}

What is the proper syntax to get back the distinct values of the field named "DataFields"?

I solved this issue using collection.distinct :

collection.distinct("DataFields",(function(err, docs){
            console.log(docs);
            assert.equal(null, err);
            db.close();
        }))

You could also do this by way of aggregation framework . The suitable aggregation pipeline would consist of the $group operator stage which groups the document by the DataFields key and create an aggregated field count which stores the documents produced by this grouping. The accumulator operator for this is $sum .

The next pipeline stage would be the $match operator which then filters the documents having a count of 1 to depict distinction.

The last pipeline operator $group then group those distinct elements and adds them to a list by way of $push operator.

In the end your aggregation would look like this:

var collection = db.collection('Fixed_Asset_Register'),
    pipeline = [
    {
        "$group": {
            "_id": "$DataFields",
            "count": {"$sum": 1}
        }
    },
    {
        "$match": { "count": 1 }
    },
    {
        "$group": {
            "_id": 0,
            "distinct": { "$push": "$_id" } 
        }
    }],
    result = collection.aggregate(pipeline).toArray(),
    distictDataFieldsValue = result[0].distinct;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM