Count messages and return a custom field (key/value)

Hello everybody,

I am trying to count how much messages exists on my db collection and return a custom key: value, If this greater than 1 countable it’s return true(1) else return false(0).

I tried the shell below, but not working yet… I think I am near to correct aggregation, but I am don’t know.

db.messages.aggregate([
	{ 
	$match: 
		{
		$and: [
            {user_id: "256f5280-fb49-4ad6-b7f5-65c4329d46e0"},
			{time: {$gt: 0, $lt: 1652471890}}
		]
		}
	},
	{ 
	$project: 
		{
		amount: $count,
		moreThanZero: 
			{
			$cond: [ { $gt: [ "$amount", 0 ] }, 1, 0]
			}
        }
	}
])

I am trying to get a $count as variable to compare it, if it’s greater than 1 my return will be 1 else 0. But it isnt working.

uncaught exception: ReferenceError: $count is not defined : @(shell):6:35

You get

because it is on the right side of a colon. It is a value. A value has to be in quote if it is not a symbol or a number. You quoted $amount correctly.

But putting $count would not do what you want to do. This is not how you count documents. You may use a $group stage with the $sum accumulator or a $count stage.

Another thing that would not work is using $amount in the same $project stage that creates it. A field created by $project or $set is only available in the next stage.

2 Likes

This answer was quite enlightening, I got help with my Mongo Query, but it also helped me a lot to understand some concepts! Thanks.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.