mongodb - Get unique keys and distinct list of values for each -


i have set of documents this:

input

[   { color: "red", size: "small" },   { color: "blue", size: "small" },   { color: "red", size: "medium" },   { color: "green", size: "medium" },   { color: "black", size: "large" } ]; 

i want create set made of each key, , distinct values each key:

output

[   { name: "color", values: ["red", "blue", "green", "black"] },   { name: "size", values: ["small" "medium", "large"] } ] 

i won't know keys of input document be.

i know how solve 2 problems separately:

  1. get keys of arbitrary document following this answer
  2. use aggregation frameworks $addtoset operator distinct list of values each key.

i in 1 pass. think it's possible use aggregation framework step 1, , pipe step 2, maybe not....

thanks

as mentioned in comment, without knowing field names in advance, can't in single pass ..., unless willing consider different schema.

here's idea example different schema collects same data, keys , values:

{ values : [  {  "k" : "color",  "v" : "red" },                {  "k" : "size",  "v" : "small" } ] } { values : [  {  "k" : "color",  "v" : "blue" },                {  "k" : "size",  "v" : "small" } ] } { values : [  {  "k" : "color",  "v" : "red" },               {  "k" : "size",  "v" : "medium" } ] } { values : [  {  "k" : "color",  "v" : "green" },                {  "k" : "size",  "v" : "medium" } ] } { values : [  {  "k" : "color",  "v" : "black" },               {  "k" : "size",  "v" : "large" } ] } 

the aggregation trivial, group on key name , use $addtoset collect values.

> db.test.aggregate({ $unwind : '$values' },       { $group :            {  _id : "$values.k",              value: { $addtoset: "$values.v" } } }) {         "result" : [                 {                         "_id" : "size",                         "value" : [                                 "large",                                 "medium",                                 "small"                         ]                 },                 {                         "_id" : "color",                         "value" : [                                 "black",                                 "green",                                 "blue",                                 "red"                         ]                 }         ],         "ok" : 1 } 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -