MongoDB-如何在$ group中使用$ in时返回数组中的匹配项? [英] MongoDB - How to return matched item in an array while using $in in $group?

查看:237
本文介绍了MongoDB-如何在$ group中使用$ in时返回数组中的匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB的聚合.

I'm using MongoDB's aggregation.

使用$in我正在检查数组中是否存在值,并且我想将匹配的对象从calificacion数组返回到calificacion_usuario字段. (我的_id在数组中是唯一的.)

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).

我尝试使用$first"返回当前元素.它不起作用,不确定为什么&使用什么.

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

我该怎么办?

示例文档:

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

查询:

    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" }

                            }
                        ]
                    }
                }
            }
        },

推荐答案

$first不能那样工作,您需要将$first替换为以下代码:

$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) */
    },
  ],
}

测试: MongoDB-Playground

参考: $ indexOfArray $ arrayElemAt

这篇关于MongoDB-如何在$ group中使用$ in时返回数组中的匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆