Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

469
Vistas
How to get array length instead of full array in find()?

I have a mongodb (using mongoose) collection ("items") which includes an array ("images") among its properties. Some example documents:

[
  {
    "_id" : ObjectId("543fa67e9672ec37ebe3d026"),
    "name" : "Alice",
    "images" : [
      { url: "http://images.com/1.jpg" },
      { url: "http://images.com/2.jpg" },
      { url: "http://images.com/3.jpg" },
    ]
  },
  {
    "_id" : ObjectId("543fa67e9672ec37ebe3d027"),
    "name" : "Bob",
    "images" : [
      { url: "http://images.com/4.jpg" },
      { url: "http://images.com/5.jpg" },
    ]
  },
]

I want to implement a query which returns - along with other document properties - the array length (and not the array contents). I know I can get the array length with

db.items.aggregate([
  { "$project" : { "_id" : 0, "imagesLength" : { "$size" : "$images" } } }
])

But I need the imagesLength values along with the documents returned with a find:

db.items.findMany(
  { ...filter },
  { name: 1, imagesCount: 1 }
);

The question is: how can I get the array length along with the find results ?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can do same as aggregation projection in find's second argument, Starting in MongoDB 4.4, as part of making find projection consistent with aggregation’s $project stage,

db.items.find(
{ ...filter },
{
  _id: 0,
  name: 1,
  images: { $size: "$images" }
})

Playground

over 4 years ago · Santiago Trujillo Denunciar

0

You can add a match stage at first in your aggregation to filter the results. Then you can project all fields needed and generate the new ones.

db.items.aggregate([
  { "$match" : { ...filter },
  { "$project" : { "imagesLength" : { "$size" : "$images" }, "name": 1 } }
])
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda