I have a collection with documents in cosmosDB .How can I group each field distinct values using mongoDB?
Here is my sample data:
{
"_id" : ObjectId("61ba65af74cf385ee93ad2c8"),
"Car_brand":"A",
"Plate_number":"5",
"Model_year":"2015",
"Company":"Tesla Motors"
},
{
"_id" : ObjectId("61ba65af74cf385ee93ad2c9"),
"Car_brand":"B",
"Plate_number":"2",
"Model_year":"2021",
"Company":"Tesla Motors",
},
{
"_id" : ObjectId("61ba65af74cf385ee93ad2ca"),
"Car_brand":"B",
"Plate_number":"2",
"Model_year":"2011",
"Company":"Lamborghini",
}
expected:
{
"Car_brand":["A","B"]
"Plate_number":["5","2"]
"Model_year":["2015","2021","2011"]
"Company":["Lamborghini","Tesla Motors"]
}
CodePudding user response:
Option1: Here is how to do in mongoDB , I guess it is similar in cosmosDB:
db.collection.aggregate([
{
$group: {
_id: null,
Car_brand: {
$push: "$Car_brand"
},
Plate_number: {
$push: "$Plate_number"
},
Model_year: {
$push: "$Model_year"
},
Company: {
$push: "$Company"
}
}
}
])
Option2: Later I have identified you need the distinct values , here is an example:
db.collection.aggregate([
{
$group: {
_id: null,
Car_brand: {
$addToSet: "$Car_brand"
},
Plate_number: {
$addToSet: "$Plate_number"
},
Model_year: {
$addToSet: "$Model_year"
},
Company: {
$addToSet: "$Company"
}
}
}
])