MarcoS
MarcoS

Reputation: 17711

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 ?

Upvotes: 1

Views: 268

Answers (3)

jakub
jakub

Reputation: 1

turivishal answer is good but for me it didn't work until I made sure that instead of :

images: { $size: "$images" }

I did any other name like :

imagesSize: { $size: "$images" }

Upvotes: 0

Givi
Givi

Reputation: 79

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 } }
])

Upvotes: 1

turivishal
turivishal

Reputation: 36104

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

Upvotes: 5

Related Questions