Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

distinct with multiple fields and with where condition in mongodb

I want to write a query equivalent to distinct and where in mongodb. the sql query is select DISTINCT key,score from GPC where note="test2" and notetwo = "meet2"

{ "_id" : ObjectId("4dc86fef6a0aa8513ab5f21c"), "key" : "SAGAR","score" : 16, "note" : "test1", "notetwo" : "meet1" } 
{ "_id" : ObjectId("4dc86ffd6a0aa8513ab5f21d"), "key" : "SAGAR456", "score" : 17, "note" : "testjh1", "notetwo" : "meetjh1" } 
{ "_id" : ObjectId("4dc8700b6a0aa8513ab5f21e"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc871686a0aa8513ab5f21f"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc871696a0aa8513ab5f220"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc8716c6a0aa8513ab5f221"), "key" : "SAGAR456", "score" : 17, "note" : "testjh1", "notetwo" : "meetjh1" } 

Expected result from the query is

[{"key" : "SAGAR33", "score" : 37}]

What is the equivalent query in mongodb. I am using mongoose to execute queries.

like image 442
niren Avatar asked Apr 16 '14 20:04

niren


People also ask

How do I use distinct aggregation in MongoDB?

You can use $addToSet with the aggregation framework to count distinct objects. Not a generic solution, if you have a large number of unique zip codes per result, this array would be very large.

How do I search for multiple fields in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

How can I get distinct values from a field in MongoDB?

To get distinct values, use distinct() in MongoDB. It finds the distinct values for a specified field across a single collection or view and returns the results in an array.

Can I use distinct with multiple columns?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.


1 Answers

You'll need to use the aggregate queries for achieving this. Here's an example that will work in shell (which can be translated to Mongoose easily):

db.gpc.aggregate([
    // your where clause: note="test2" and notetwo = "meet2"
    {"$match" : {note:"test2", notetwo:"meet2"}}, 
    // group by key, score to get distinct
    {"$group" : {_id : {key:"$key", score:"$score"}}}, 
    // Clean up the output
    {"$project" : {_id:0, key:"$_id.key", score:"$_id.score"}}
])

Output:

{ "result" : [ { "key" : "SAGAR33", "score" : 37 } ], "ok" : 1 }
like image 95
Anand Jayabalan Avatar answered Oct 01 '22 04:10

Anand Jayabalan