1

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 ?

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.