mongodb - How to define a query which returns all documents with a same field -


i create query checking documents in database have same field value.

e.g. got 100 documents stored , 2 of them looks this:

document 1:

{     "_id":32143242,     "specialfield":12 } 

document 2:

{     "_id":787878,     "specialfield":12 } 

so how 2 documents if don't know ids or specialfield-value?

this grouping operation can performed using mongodb aggregation framework.

sample data

> db.foo.find().pretty(); { "_id" : objectid("515ead9c7bb40c6a51b16a68"), "value" : 12 } { "_id" : objectid("515ead9d7bb40c6a51b16a69"), "value" : 12 } { "_id" : objectid("515ead9f7bb40c6a51b16a6a"), "value" : 14 } { "_id" : objectid("515eada07bb40c6a51b16a6b"), "value" : 8 } 

sample grouping operation

> db.foo.aggregate({$group :      { _id: "$value",        count : {$sum : 1},        ids: { $addtoset : "$_id" } } }); 

this return groups of equal value along count , respective ids:

{         "result" : [                 {                         "_id" : 8,                         "count" : 1,                         "ids" : [                                 objectid("515eada07bb40c6a51b16a6b")                         ]                 },                 {                         "_id" : 14,                         "count" : 1,                         "ids" : [                                 objectid("515ead9f7bb40c6a51b16a6a")                         ]                 },                 {                         "_id" : 12,                         "count" : 2,                         "ids" : [                                 objectid("515ead9d7bb40c6a51b16a69"),                                 objectid("515ead9c7bb40c6a51b16a68")                         ]                 }         ],         "ok" : 1 } 

you should read documentation of aggregation framework , understand limitations.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -