简体   繁体   中英

find the mongo db unique documents

I have a collection called location in mongodb. It has fields location:

 (_id,country,region,city,doctype,name)

There may be multiple documents( records ) with same name. I want to find all documents and select fields

_id,doctype,and name

with unique name. I am new to mongo db and please help me.

Do a map reduce to count the name that are multiple:

db.collection.mapReduce(
    function(){emit(this.name);},
    function(key,values){
        sum=0;
        for(var i=0;i<values.length;i++){
           sum+=values[i];
        }
        return sum;
    },
    {out:"count_per_name"}
);

This will create a collection named "count_per_name". Query that to find the names with count bigger than 1.

You want to use the .aggregate function with the $group operator:

db.collection.aggregate([
    { "$group": {
        "_id": {
            "_id": "$_id",
            "doctype": " $doctype",
            "name": "$name"
        }
    }}
])

This is kind of the equivalent of the SQL "GROUP" operator. See the SQL TO Aggregation mapping in the MongoDB manual for more examples.

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