简体   繁体   中英

Count in aggregation MongoDB

I have a document that contains companies that have offices all over the world. These offices are in an array. One of the values is the city and I need to know exactly which companies have 2 offices in "San Francisco".

The Document:

_id:52cdef7c4bab8bd675297d8b
name:"AdventNet"
.
.
.
.
Offices:Array
   0:
     Description:"Headquarters"
     .
     .
     city:"San Francisco"

My Solution:

db.companies.aggregate(
      {$group:{_id:{city:"$offices.city"},count:{$sum:1}}},
      {$match:{$and: [{"_id.city":"San Francisco"},{count:2}]}})

But it doesn't work. Any Idea?

Demo - https://mongoplayground.net/p/qnTm42c0Y1S

db.collection.aggregate([
  {
    $match: { "Offices.city": "San Francisco" } // filter to reduce records going to $map in the next pipeline 
  },
  {
    $set: {
      haveOfficeInCIty: {
        $size: { // get the size of the filtered array
          $filter: { // filter the array
            input: "$Offices",
            as: "office",
            cond: {
              $eq: [ "$$office.city", "San Francisco" ] // filter by city
            }
          }
        }
      }
    }
  },
  {
    $match: {
      haveOfficeInCIty: { $eq: 2 } // filter where count is 2
    }
  }
])
  • $filter to iterate loop of city and filter city by "San Francisco"
  • $size to get size of filtered city
  • match expression $expr condition size of city is 2
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $eq: [
          {
            $size: {
              $filter: {
                input: "$Offices.city",
                cond: { $eq: ["$$this", "San Francisco"] }
              }
            }
          },
          2
        ]
      }
    }
  }
])

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM