kissjs / node-mongoskin

The wrapper for node-mongodb-native.
MIT License
1.52k stars 164 forks source link

How to use method distinct? #146

Open bengle opened 10 years ago

bengle commented 10 years ago

db.collection.distinct('xxx',function(err,docs){...}) I used it like this,but it seems not correct.

mbejda commented 9 years ago

The only way I got distinct working with mongo skin is by doing this :

var store = mongo.db(connectionString, ackOptions);
store.open(function(err,resp){
     resp.collection(this.options.collection, {strict: true}, function(err, myCollection) {
        myCollection.distinct('tag',function(err,res){
            console.log(err)
            console.log(res)
        })
    });
})
jmartorell commented 8 years ago

Distinct function goes via native MongoDB driver, no code is added by MongoSkin AFAIK. distinct returns an array of keys, but only that.

distinct(key, query, callback)

You can use the result at the callback as a new query.

Imagine you want to get all the authors who greeted at least once in their posts:

var collection = this.db.collection('posts');
    collection.distinct( "author", {
      message: /^hi/
    }, function(error, keys) {
        collection.findItems({
            "author": { $in: keys}
        },
            function (error, results) {
              if (!error) {
                console.log(results)
              }
            });
    });

This works for me, I hope this issue can be closed.