Search code examples
javascriptnode.jsarraysmongodbmongoose

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 ?


Solution

  • 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