简体   繁体   English

如何使用nodejs和mongodb获取另一个对象内部的对象?

[英]How do I get an object that is inside another with nodejs and mongodb?

I need to obtain the information contained in the array named detalleInsumos through the _id of that object.我需要通过该对象的_id获取名为detalleInsumos的数组中包含的信息。

I have tried many ways, but I still have not found the solution to my problem, since it always shows me all the objects of that document, which does not work for me.我尝试了很多方法,但我仍然没有找到解决我的问题的方法,因为它总是向我显示该文档的所有对象,这对我不起作用。

This is the document from which I need to get that information:这是我需要从中获取该信息的文档:

{
    "_id":{"$oid":"5f9041196462be3c5ca1e53d"},
    "codigoFinca":"000",
    "nombreFinca":"PROVINCIANA",
    "fechaRegistro":"2020-10-21",
    "semanaRegistro":"43",
    "usuarioRegistro":"cotorreo",
    "trabajadoresFinca":[
        {
            "porcentajeRecargo":0,
            "_id":{"$oid":"5f9041196462be3c5ca1e53e"},
            "udpTrabajador":[
                {
                    "unidadesAPagar":null,
                    "valorUnidad":"",
                    "areaLaborada":"2",
                    "semanaNormal":null,
                    "semanaAtrazos":null,
                    "_id":{"$oid":"5f9041196462be3c5ca1e53f"},
                    "detalleInsumos":[
                        {"_id":{"$oid":"5f9041196462be3c5ca1e540"},
                         "codigoInsumo":"20000001",
                         "descripcionInsumo":"NYLON X 5 KILOS",
                         "cantidadAplicada":"153",
                         "idRDI":"426715",
                         "idDetalleSaldo":"24070"
                        }
                    ],
                    "codigoLabor":"101",
                    "nombreLabor":"AMARRE",
                    "loteLaboro":"1"
                }
            ],
            "codigoTrabajador":"0000",
            "nombresTrabajador":"HUMBERTO  MENA MOSQUERA",
            "horasJornada":"10",
            "horasLaboradas":"10"
        }
    ],
    "createdAt":{"$date":"2020-10-21T14:09:29.876Z"},
    "updatedAt":{"$date":"2020-10-21T15:09:51.657Z"},
    "__v":0
}

And this is what I have tried from nodejs:这就是我从 nodejs 中尝试过的:

const consultauno = await Modelo.findOne({
                'trabajadoresFinca.udpTrabajador.detalleInsumos._id': new ObjectId(idInsumo)
            },
            {
                "trabajadoresFinca.udpTrabajador.detalleInsumos": 1
            });
            console.log(consultauno);

You can try,你可以试试,

  • $match your condition $match你的条件
  • $reduce to iterate loop of trabajadoresFinca array, second $reduce to iterate loop of udpTrabajador array, $filter to get matching object from detalleInsumos array, $reduce迭代trabajadoresFinca数组的循环,第二个 $reduce 迭代udpTrabajador数组的循环, $filterdetalleInsumos数组中获取匹配的对象,
  • $arrayElemAt will get first object from array when condition match $arrayElemAt将在条件匹配时从数组中获取第一个对象
  • $mergeObjects will merge initialValue or reduce and matching object $mergeObjects将合并 initialValue 或 reduce 并匹配对象
const consultauno = await Modelo.aggregate([
  {
    $match: {
      "trabajadoresFinca.udpTrabajador.detalleInsumos._id": ObjectId(idInsumo)
    }
  },
  {
    $project: {
      detalleInsumos: {
        $reduce: {
          input: "$trabajadoresFinca",
          initialValue: {},
          in: {
            $mergeObjects: [
              "$$value",
              {
                $reduce: {
                  input: "$$this.udpTrabajador",
                  initialValue: {},
                  in: {
                    $mergeObjects: [
                      "$$value",
                      {
                        $arrayElemAt: [
                          {
                            $filter: {
                              input: "$$this.detalleInsumos",
                              cond: {
                                $eq: ["$$this._id", ObjectId(idInsumo)]
                              }
                            }
                          },
                          0
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Playground操场


Second approach, you can use $unwind ,第二种方法,你可以使用$unwind

  • $match your conditions $match你的条件
  • $unwind deconstruct trabajadoresFinca array $unwind解构trabajadoresFinca数组
  • $unwind deconstruct udpTrabajador array $unwind解构udpTrabajador数组
  • $unwind deconstruct detalleInsumos array $unwind解构detalleInsumos数组
  • $match your conditions $match你的条件
  • $project to show required fields $project显示必填字段
const consultauno = await Modelo.aggregate([
  {
    $match: {
      "trabajadoresFinca.udpTrabajador.detalleInsumos._id": ObjectId(idInsumo)
    }
  },
  { $unwind: "$trabajadoresFinca" },
  { $unwind: "$trabajadoresFinca.udpTrabajador" },
  { $unwind: "$trabajadoresFinca.udpTrabajador.detalleInsumos" },
  {
    $match: {
      "trabajadoresFinca.udpTrabajador.detalleInsumos._id": ObjectId(idInsumo)
    }
  },
  {
    $project: {
      trabajadoresFinca: "$trabajadoresFinca._id",
      udpTrabajador: "$trabajadoresFinca.udpTrabajador._id",
      detalleInsumos: "$trabajadoresFinca.udpTrabajador.detalleInsumos"
    }
  }
])

Playground操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM