2

Suppose I have a collection with an array field:

{
  title: String,
  users: [String],
}

Now I need to query a list of documents from the collection, using only the length of users in each of it, without actual elements in users array (because it maybe large, it won't be worth to fetch them from db and count the length):

Collection.find({}).sort({ _id: -1 })

Is it possible?

2
  • Do you want to count the elements inside the users array? Commented Dec 13, 2018 at 9:28
  • @AnthonyWinzlet yeah, exactly Commented Dec 13, 2018 at 9:32

1 Answer 1

2

You can use $size aggregation operator to find the length of the users array

db.collection.aggregate([
  { "$project": { "userLength": { "$size" :"$users" }}}
])

If you want to find all the users array length exists in the database

db.collection.aggregate([
  { "$group": {
    "_id": null,
    "allUsersArrayLength": { "$sum": { "$size": "$users" }}
  }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

It will not affect the performance of the query. Only add a new key with every document. Better then "finding all the document" and check the length by iterating. And even most of the things a database can better do with respect to javascript code.

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.