Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb to return object from facet

Is it possible to have facet to return as an object instead of an array? It seems a bit counter intuitive to need to access result[0].total instead of just result.total

code (using mongoose):

        Model
            .aggregate()
            .match({
                "name": { "$regex": name },
                "user_id": ObjectId(req.session.user.id),
                "_id": { "$nin": except }
            })
            .facet({
                "results": [
                    { "$skip": start },
                    { "$limit": finish },
                    {
                        "$project": {
                            "map_levels": 0,
                            "template": 0
                        }
                    }
                ],
                "total": [
                    { "$count": "total" },
                ]
            })
            .exec() 
like image 294
A. L Avatar asked Aug 07 '18 03:08

A. L


2 Answers

Each field you get using $facet represents separate aggregation pipeline and that's why you always get an array. You can use $addFields to overwrite existing total with single element. To get that first item you can use $arrayElemAt

Model
    .aggregate()
    .match({
        "name": { "$regex": name },
        "user_id": ObjectId(req.session.user.id),
        "_id": { "$nin": except }
    })
    .facet({
        "results": [
            { "$skip": start },
            { "$limit": finish },
            {
                "$project": {
                    "map_levels": 0,
                    "template": 0
                }
            }
        ],
        "total": [
            { "$count": "total" },
        ]
    })
    .addFields({
        "total": {
            $arrayElemAt: [ "$total", 0 ]
        }
    })
    .exec()
like image 113
mickl Avatar answered Sep 19 '22 22:09

mickl


You can try this as well

Model
.aggregate()
.match({
  "name": { "$regex": name },
  "user_id": ObjectId(req.session.user.id),
  "_id": { "$nin": except }
})
.facet({
  "results": [
    { "$skip": start },
    { "$limit": finish },
    {
      "$project": {
        "map_levels": 0,
        "template": 0
      }
    }
  ],
  "total": [
    { "$count": "total" },
  ]
})
.addFields({
  "total": {
    "$ifNull": [{ "$arrayElemAt": [ "$total.total", 0 ] }, 0]
  }
})
.exec()
like image 37
Ashh Avatar answered Sep 20 '22 22:09

Ashh