A
A
Anton2021-09-15 14:18:34
NoSQL
Anton, 2021-09-15 14:18:34

How to count the number of matching fields in mongoDb with and without a condition?

Hello.
Let's say there is a users collection with documents of the form (I intentionally omit _id):

{
    user_id:1,
    group_id:100,
    description:null
},
{
    user_id:1,
    group_id:102,
    description:null
},
{
    user_id:1,
    group_id:100,
    description:"text"
},
{
    user_id:2,
    group_id:102,
    description:"another text"
},
{
    user_id:3,
    group_id:101,
    description:"another text"
}

1. How to display the result with a count for each line of the form (an example is purely for understanding the logic):
{
user_id: [
1: 
      count:3,
2:
      count:1,
3:
      count:1],
group_id: [
100:
      count:2,
101:
      count:1,
102:
      count:2],
description: [
null:
      count: 2,
"text":
      count: 1,
"another text":
      count:2]
}


2. How to group by "user_id" and count remaining fields?

{
user_id: 1,
group_id: [
100:
      count: 2,
102:
      count: 1],
description: [
null:
      count: 2,
"text":
      count: 1]
},

{
user_id: 2,
group_id: [
102:
      count: 1],
description: [
"another text":
      count: 1]
},

{
user_id: 3,
group_id: [
101:
      count: 1],
description: [
"another text":
      count: 1]
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question