Varun Kumar Medam
Varun Kumar Medam

Reputation: 91

Return total fields count in mongodb

Is it possible to retrieve the total fields count with respect to fields name in a single query from a collection?

I am expecting a result like this

{
  "field_1":101,
  "field_2":93,
  "field_3":1
}

Upvotes: 1

Views: 106

Answers (2)

turivishal
turivishal

Reputation: 36144

You can try,

  • $project convert root object to array using $objectToArray, this will create k(key) and v(value) structure of array
  • $unwind deconstruct root array
  • $group by k(key) and get total fields count using $sum
  • $group by null and construct an array with k(key) and v(value) fields format
  • $replaceRoot to replace object after converting from array using $arrayToObject
db.collection.aggregate([
  { $project: { root: { $objectToArray: "$$ROOT" } } },
  { $unwind: "$root" },
  {
    $group: {
      _id: "$root.k",
      total: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: null,
      root: {
        $push: { k: "$_id", v: "$total" }
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $arrayToObject: "$root"
      }
    }
  }
])

Playground

Upvotes: 1

user12582392
user12582392

Reputation:

Yes

Playground

db.collection.aggregate({
  $group: {
    _id: null,
    field_2: {
      $push: {
        $cond: [
          "$field_2",
          1,
          0
        ]
      }
    },
    field_1: {
      $push: {
        $cond: [
          "$field_1",
          1,
          0
        ]
      }
    }
  }
},
{
  $project: {
   _id:0,
    field_1: {
      $sum: "$field_1"
    },
    field_2: {
      $sum: "$field_2"
    }
  }
})

Be aware:

When is true, $exists matches the documents that contain the field, including documents where the field value is null

Upvotes: 1

Related Questions