MongoDB distinct, return all fields
Asked Answered
H

0

8

I'm using MongoDB and the node-mongodb-native driver.

I'm trying to return all records with a distinct attribute.

This seems to work, however it only returns the value which I'm checking for being distinct, not all values in each document.

This is what I have tried to return just the name field, I've also tried without it and variations of, but it always only returns the item_id's in an array.

    this.collection.distinct("item_id", [{"name" : true}, {sold : {"$exists" : true}}], function(err, results) {
        if (err) {
            callback(err);
        } else {
            console.log(results);
        }
    });

Any suggestions how to get all the data from each document?

Thank you!

EDIT: Using Map Reduce

So, I just setup the start of a map reduce, using the node-mongodb-native, here's what I have so far:

    var map = function() {
        emit(this._id, {"_id" : this._id, "name" : this.name});
    }

    var reduce = function(key, values) {

        var items = [];

        values.forEach(function(v) {
            items.push(v);
        }); 

        return {"items" : items};
    }

    this.collection.mapReduce(map, reduce, {out: "res"}, function(err, results) {
        if (err) {
            console.log(err);
        } else {
            console.log(results);
        }
    });

I know the logic isn't in there for distinct, but the results is the db object, I can't use 'toArray' on it. Any ideas why this might be?

Hoe answered 13/8, 2012 at 17:21 Comment(5)
Youll need to use MR unless your running 2.2 in which case this can be done with the aggregation framework I believe.Trammel
@Trammel Thank you, I've updated my post and included a Map Reduce example; any suggestions to the results issue?Hoe
The result will actually be a message telling you if it has succeeeded for not, you must get the out Db from the returned structure of the MR call and then query the output table.Trammel
I don't understand what you're trying to do. If you get all of the distinct values, that means that there will (in the general case) be multiple documents which have that distinct value for the key. Can you show a couple of sample documents & the output you'd like to get?Orthopedic
The OP has started a new threa for this here: #11941236Trammel

© 2022 - 2024 — McMap. All rights reserved.