I am trying to work out a way of getting all unique pairs of a key-value array property across all documents in a collection.
The array ‘Tags’ property looks like this on say two documents:
Document1:
{
Tags: [
{ k: “key1”, v: “value1” },
{ k: “key2”, v: “value2” },
…
]
}
Document2:
{
Tags: [
{ k: “key1”, v: “value3” }
…
]
}
With expected query output something like this:
[
{ k: “key1”, v: “value1” },
{ k: “key2”, v: “value2” }
{ k: “key1”, v: “value3” },
…
]
or this:
[
{
k: “key1”,
values: [
“value1”,
“value3”,
…
]
},
{
k: “key2”,
values: [
“value2”,
…
]
}
…
},
{
k: “key2”,
values: [
“value2”,
…
]
}
]
I have an index Tags_k_1_Tags_v_1, but I cannot get a query to return that uses it. I cannot use distinct() as more than one field is required. I have tried aggregation by unwinding the array, then grouping by k, and addToSet the values. No luck using the index. There are possibly millions of documents that will grow over time, so it is important an index is used.
Any help appreciated.