0

The problem I am facing is below:

I have a MongoDB document whose structure is as follows

"name": "XYZ",
"array":[
 {
  "value": "Alpha"
 },
 {
  "value": "Beta"
 },
 {
  "value": "Alpha"
 },
]

and I have to count how many objects have value Alpha. I have tried the following two queries but both only give me value 1.

db.current_database.find({array: {$elemMatch: {value: "Alpha"}}}).count()
db.current_database.find({'array.value': 'Alpha'}).count()

1 Answer 1

1

The find collection method returns documents, not fragments.

A few options to count occurrances of elements in an array:

Most languages provide a method to filter/reduce/count elements in an array, so this should be fairly straightforward on the client side.

The MongoDB aggregation framework provides $reduce, $filter, $size, $group, $unwind, and a few other operators that might be useful in this situation.

One possible solution using $reduce:

db.current_database.aggregate([
  {$match: {"array.value": "Alpha"}},
  {$addFields:{
      count: {
          $reduce: {
              input: "$array",
              initialValue: 0,
              in: {
                  $cond: {
                     if: {$eq: ["$$this.value", "Alpha"]},
                     then: {$sum: ["$$value", 1]},   
                     else: "$$value"
                  }
               }
           }
       }
  }}
])
Sign up to request clarification or add additional context in comments.

4 Comments

I get error "2020-09-17T13:02:19.163-0500 E QUERY [js] Error: command failed: { "ok" : 0, "errmsg" : "Use of undefined variable: value", "code" : 17276, "codeName" : "Location17276" } : aggregate failed : _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:18:14 _assertCommandWorked@src/mongo/shell/assert.js:536:17 assert.commandWorked@src/mongo/shell/assert.js:620:16 DB.prototype._runAggregate@src/mongo/shell/db.js:260:9 DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1062:12 @(shell):1:1"
How does your test run differ from mongoplayground.net/p/fIJmJxuFJfR?
Sorry my bad, I just messed up with keyword "value". Now, this does return a document, how can one just get a value.
All mongodb queries and commands return a document or cursor. You can use $project to limit which fields are returned. The driver or shell may have convenience functions to show the value of one field. For instance, adding .next().count to that sample query in the shell will return just the value of the count field from the first document.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.