How to return the number of elements of a document property in a collection in Mongodb

Asked

Viewed 389 times

3

Hello, I have a collection that has the documents with the format below:

{
    "_id"   : ObjectId("..."),
    "checked": true,
    "styles": ["foo", "bar", "bin"]
}

I need to add the array size styles for all documents that meet a filter, ex:

db.test.find({ checked: { $exists : true } })/* aqui entraria o resto da query*/

How should be the query so I can generate this sum (in Mongodb). If I were to do after returning the result I believe I would have a loss of performance. We can say that it would be something like the code below after the return:

function getData(filter) { 
    /* retorna o resultado esperado*/ 
}

var soma = getData({checked:true})
    .map(x=>x["styles"].length)
    .reduce((a,b) => a+=b, 0)

/* soma representaria a soma do tamanho da propriedade styles */

How to do?

2 answers

4


I found the solution below:

db.test.aggregate([
    {$match: {checked: true}},
    {$project: {size: {$size : "$styles"}}},
    {$group: {_id: null, total: {$sum: "$size"}}}
])

2

Leandro, just add . Count() at the end of the query.

db.test.find({ checked: { $exists : true } }).count()

With this he will add up all the records that attend the checked: true and will make a sum.

Continuation:

I was able to get the total of Tyles of each object:

db.test.aggregate([
{
  $project: {
     totalStyles: { $cond: { if: { $isArray: "$styles" }, then: { $size: 
  "$styles" }, else: "NA"} }
  }, 
}
] )

I think that already helps you. I would have to make a condition for everyone to have checked: true, then add the value of that variable that returns the total of elements.

  • but I don’t want to know the number of documents, I want the sum of the field size styles that exists in each document. In the example I have 1 document with 3 items in the field, then the result will be 3

  • 1

    This field is an array? or an object?

  • the Styles field is an array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.