MongoDB - How to return matched item in an array while using $in in $group?

纵然是瞬间 提交于 2020-05-16 02:19:21

问题


I'm using MongoDB's aggregation.

Using $in I'm checking if a value exists in an array or not, And I want to return the matched object from calificacion array into calificacion_usuario field. (my _id is unique in the array).

I tried using $first" to return the current element. It's not working, not sure why & what to use.

How can I do it?

Sample Doc :

{
 "cargo" : "Presidente",
 "calificacion" : [ 
    {
        "_id" : "5e894ae6fa9fd23780bcf472",
        "estrellas" : 3
    }, 
    {
        "_id" : "5e895187fa9fd23780bcf478",
        "estrellas" : 5
    }
]}

Query :

    Politico.aggregate([
        {
            $group: {
                _id: "$cargo",
                nuevo_formato: {
                    $push: {
                        $mergeObjects: [
                            "$$ROOT",
                            {
                                "calificacion_promedio": { $avg: "$calificacion.estrellas" },
                                "calificacion_usuario": { $cond: [{ $in: [req.body.id_usuario, "$calificacion._id"] }, "$first", false] },
                                "calificacion_numero_encuestas": { $size: "$calificacion" }

                            }
                        ]
                    }
                }
            }
        },

回答1:


$first doesn't work that way, You need to replace $first with below code :

{
  $arrayElemAt: [ /** Get an element from 'calificacion' based on position */
    "$calificacion",
    {
      $indexOfArray: ["$calificacion._id", req.body.id_usuario], /** Check in which position 'req.body.id_usuario' exists (will be a number) */
    },
  ],
}

Test : MongoDB-Playground

Ref : $indexOfArray, $arrayElemAt



来源:https://stackoverflow.com/questions/61038004/mongodb-how-to-return-matched-item-in-an-array-while-using-in-in-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!