1

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.