Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

468
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda