问题
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