2

I have a collection of documents with an array (set in this case): my_array

I'm adding things to this set periodically

collection.find({ "_id": target_id })
.upsert().update({ '$addToSet':{ 'my_array': new_entry }})

Many of the logical operations I perform on this DB are based on this sub-array's size. So I've created a field (indexed) called len_of_array. The index is quite critical to my use case.

In the case where this is a true array and not a set, the $incr would work beautifully in the same update

However, since the sub-collection is a set, the length of the collection, my_array, may or may not have changed.

My current solution:

Call this periodically for each target_id, but this requires performing a find in order to get the correct len_of_array

collection.find({ '_id': target_id})
.upsert().update({ '$set':{ 'len_of_array': new_length }})

My Question Is there a way to set a field of a document to the indexed size of a sub-array in the same document in a single update?

1 Answer 1

2

You don't need the field length_of_array in order to query by its size. There is the $size operator. Which would save you the periodical update, too.

Let's say you want to find all documents for which the length of my_array is greater than 2:

db.coll.find({ "my_array":{ "$size" :{ "$gt": 2 }}})
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Am I correct in assuming that there is no way to index $size I will update my question to explain that the field len_of_array is also indexed.
@puj Simply index the array.
Is this correct? My recent experience suggests that indexing an array (e.g. putting an index on a "doc.arr" field) does not allow for indexed count, but rather the count will scan the document. Whereas searching for arrays that contain the value "x" will use the index.
@mils Curious. Will check that. I think I had checked it when I wrote the answer, but I am not too sure.

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.