Notification texts go here Contact Us Buy Now!

MongoDB aggregation Query;: find documents having count more than 1

MongoDB Aggregation Query: Find Documents Having Count More Than 1

In MongoDB, you can use aggregation queries to perform complex data processing operations. One common task is to find documents that have a count greater than 1.

Since MongoDB version 5.0, one option is to use $setWindowFields:

db.collection.aggregate([
  {$setWindowFields: {
      "partitionBy": "$uniqueKey",
      "sortBy": {"cust_id": 1},
      "output": {
        "count": {
          "$sum": 1,
          "window": {documents: ["unbounded", "unbounded"]}
          }
        }
      }
  }},
  {$match: {count: {$gt: 1}}},
  {$project: {_id: 0, "uniqueKey": 1, "cust_name": 1}}
])

See how it works on the playground example

This will prevent pushing all the documents with the same uniqueKey into one big document.

Before mongoDB 5.0:

One option is to use $group, but you need to use $push on your $group and $unwind afterwards. This option may be problematic if you have many documents with the same uniqueKey

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.