Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

mongodb get distinct records

I am using mongoDB in which I have collection of following format.

{"id" : 1 , name : x  ttm : 23 , val : 5 }
{"id" : 1 , name : x  ttm : 34 , val : 1 }
{"id" : 1 , name : x  ttm : 24 , val : 2 }
{"id" : 2 , name : x  ttm : 56 , val : 3 }
{"id" : 2 , name : x  ttm : 76 , val : 3 }
{"id" : 3 , name : x  ttm : 54 , val : 7 }

On that collection I have queried to get records in descending order like this:

db.foo.find({"id" : {"$in" : [1,2,3]}}).sort(ttm : -1).limit(3)

But it gives two records of same id = 1 and I want records such that it gives 1 record per id.

Is it possible in mongodb?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There is a distinct command in mongodb, that can be used in conjunction with a query. However, I believe this just returns a distinct list of values for a specific key you name (i.e. in your case, you'd only get the id values returned) so I'm not sure this will give you exactly what you want if you need the whole documents - you may require MapReduce instead.

Documentation on distinct: http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...