简体   繁体   中英

mongoose - aggregating data

I'm trying to figure out how to use aggregate with mongoose with the following code below:

    const Model = db.model(which, schema)
    var regex = new RegExp(name, "g")
    const query =
        Model
            .find({
                name: regex
            })
            .where("user_id").equals(req.session.user.id)

    if (except) 
    {
        if (Array.isArray(except))
        {
            query
                .where("_id").nin(except)
        }
        else 
        {
            query
                .where("_id").neq(except)
        }
    }  

    return await
        query
            .skip(start)
            .limit(finish)
            .lean()
            .exec()

What I'm trying to do is get the total (that wasn't limited) as well. Of course I could remove skip and limit and use count , and run it a second time, but I think aggregate is suitable in this situation?

You can try below aggregation

db.collection.aggregate([
  { "$facet": {
    "data": [
      { "$match": {
        "name": { "$regex": name },
        "user_id": mongoose.Types.ObjectId(req.session.user.id),
        "_id": { "$nin": except }
      }},
      { "$skip": start },
      { "$limit": finish }
    ],
    "count": [
      { "$match": {
        "name": { "$regex": name },
        "user_id": mongoose.Types.ObjectId(req.session.user.id),
        "_id": { "$nin": except }
      }},
      { "$count": "count" }
    ]
  }}
])

To do once (chain) do this:

        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
                        }
                    }
                ],
                "count": [
                    { "$count": "total" },
                ]
            })
            .exec()

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