Hello,
I’m relatively new to MongoDB.
I have to make a backend, where i can count a multi level object structure items. Every time a data arrive i have to insert into the db or if it’s exists in the db then increment the counter. But i have to do it in every level.
Example:
On an another database i have a lot of data with this structure:
"a":[
{
"a_id":1,
"b":[
{
"b_id":2,
"c":[
{
"c_id":3,
someOtherMetadata...
},...
],
someOtherMetadata...
},...
],
someOtherMetadata...
},...
]
With a lot of “A”-s and a lot of “B”-s inside every “A” and a lot of “C”-s inside every “B”.
And i have to store and count it in MongoDB if somebody select one “C” (the deepest level) item. I want to store the same structure without metadata and with a counter in the db but only add item on the first call.
"a":[
{
"a_id":1,
"count":1,
"b":[
{
"b_id":2,
"count":1,
"c":[
{
"c_id":3,
"count":1
},...
],
},...
],
},...
]
For example i have an initially empty db and the first call arrive with: {"a_id":1, "b_id":1, "c_id":1}
(The call is always contains the deepest level id and all id above)
And it inserts to the db:
"a":[
{
"a_id":1,
"count":1,
"b":[
{
"b_id":1,
"count":1,
"c":[
{
"c_id":1,
"count":1
}
]
}
]
}
]
And the next call with: {"a_id":1, "b_id":2, "c_id":1}
Then the db become this:
"a":[
{
"a_id":1,
"count":2,
"b":[
{
"b_id":1,
"count":1,
"c":[
{
"c_id":1,
"count":1
}
]
},
{
"b_id":2,
"count":1,
"c":[
{
"c_id":1,
"count":1
}
]
}
]
}
]
The “A” counter incremented and the new “B” inserted into the A’s array.
The next call with: {“a_id”:1, “b_id”:1, “c_id”:2}
Then the db become this:
"a":[
{
"a_id":1,
"count":3,
"b":[
{
"b_id":1,
"count":2,
"c":[
{
"c_id":1,
"count":1
},
{
"c_id":2,
"count":1
}
]
},
{
"b_id":2,
"count":1,
"c":[
{
"c_id":1,
"count":1
}
]
}
]
}
]
The next call with: {“a_id”:1, “b_id”:1, “c_id”:1}
Then the db become this:
"a":[
{
"a_id":1,
"count":4,
"b":[
{
"b_id":1,
"count":3,
"c":[
{
"c_id":1,
"count":2
},
{
"c_id":2,
"count":1
}
]
},
{
"b_id":2,
"count":1,
"c":[
{
"c_id":1,
"count":1
}
]
}
]
}
]
The count of an item is always the sum of all nested items count inside it.
If “A” exists then increment, otherwise insert. If “B” exists inside the “A” then increment, otherwise insert and so on with “C”…
I don’t have any idea how i can achieve this.