How to find different field values ​​in MongoDB collection using Node MongoClient

In my MEAN application, I need to find various values ​​of a field named "DataFields" from my collection "Fixed_Asset_Register" using (non-mango) 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 correct syntax to return individual values ​​for a field named "DataFields"?

+3


source to share


2 answers


I solved this problem using collection.distinct :



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

      

+5


source


You can also do this with an aggregation framework . A suitable aggregation pipeline would consist of a step that groups the document using a key and create an aggregated field that stores the documents generated by this grouping. The battery operator is for this . $group

DataFields

count

$sum

The next step in the pipeline is the operator, who then filters documents that have a 1 to show the difference. $match

count

The last operator in the pipeline then groups these individual items and adds them to the list using the operator. $group

$push



As a result, your aggregation will 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;

      

0


source







All Articles