Reputation: 1327
Below given are my 4 documents with exact structure in mongo collection, I have such 276 documents in my collection. I simply want to get the distinct "Campaign Names" from my collection.
Values and Header arrays are one to one mapped:
{
"_id" : "ObjectId("58a4adb4ef2bf41444c79e5b1"),
"Status" : false,
"Headers" : [
"Campaign Name",
"Ad Set Name",
"Ad Name",
"URL Tags",
],
"Values" : [
"Campaign 1",
"Adset 1",
"Ad 1",
"url tag1"
]
}
,
{
"_id" : "ObjectId("58a4adb4ef2bf41444c79e5b2"),
"Status" : false,
"Headers" : [
"Campaign Name",
"Ad Set Name",
"Ad Name",
"URL Tags",
],
"Values" : [
"Campaign 2",
"Adset 2",
"Ad 2",
"url tag 2"
]
},
{
"_id" : "ObjectId("58a4adb4ef2bf41444c79e5b3"),
"Status" : false,
"Headers" : [
"Campaign Name",
"Ad Set Name",
"Ad Name",
"URL Tags",
],
"Values" : [
"Campaign 2",
"Adset 2",
"Ad 2",
"url tag 2"
]
},
{
"_id" : "ObjectId("58a4adb4ef2bf41444c79e5b4"),
"Status" : false,
"Headers" : [
"Campaign Name",
"Ad Set Name",
"Ad Name",
"URL Tags",
],
"Values" : [
"Campaign 4",
"Adset 4",
"Ad 4",
"url tag 4"
]
}
Needed Output:
Campaign 1,Campaign 2,Campaign 4
As Campaign 2 is reaping twice, so i want it to appear one time only as mentioned above.
Please help!!
Upvotes: 0
Views: 902
Reputation: 37018
Can be done fairly simple with mapReduce:
db.collection.mapReduce(
function(){
for(var i = 0; i < this.Headers.length; i++) {
if (this.Headers[i] === "Campaign Name" && i in this.Values) {
emit(this.Values[i], 1);
}
}
},
function(header, values) {
return 1
},
{out: {inline: 1}}
)
Upvotes: 2
Reputation: 75914
This answer depends on fixed index for the value you are looking for in all documents.
So assuming you always take care of inserting data at the right position in both Headers
and Values
.
For Campaign Name
the index is 0 in Values
array
You can get away with below query
db.collection.distinct("Values.0").
Upvotes: 3