Description
Description
As of mongodb version 4.4 the client supports the size operator while doing projection during find operation.
So, lets say if I have a collection which has array of sub documents and I want the size of those documents, I can write
db.collection.find({},{childCollectionSize:{$size:"$childArray"}})
I have been trying to do different ways to achieve the same via find but unfortunately this does not execute correctly, it ignores the projection part.
collectionRepository.find(
"{'status' : 'IN_PROGRESS',userId:?1 },{childCollectionSize:{$size:'$childArray'},userId:1,itemId:1,version:1,itemType:1 }",
loggedInUser
).project(SomeClass::class.java)
I am using kotlin. What happens is that the projection class specified takes over as projection properties than the one defined in the find query. So, the above execution query is like
{"find": "collection", "filter": {"status": "IN_PROGRESS", "userId": "e422f969-1b02-4949-aca9-79a954d6c8e2"}, "projection": {"itemId": 1, "itemName": 1, "itemType": 1, "id": 1, "version": 1, "userId": 1, "childCollectionSize": 1}, "batchSize": 16, "$db": "some-db", "lsid": {"id": {"$binary": {"base64": "someid", "subType": "04"}}}}
This can be achieved via the aggregations but when the find operation supports it with mongo client, there should be a way for find function too
Implementation ideas
I think we can create an overloaded find function with arg to specify the projection configuration , maybe in json, that overrides the properties/attributes of the projection class but is mapped to the properties specified.
The other way is , add support annotation in the projection class so that custom field mapping query can be executed. So, something like:
@ProjectionFor(SomeClass)
class MyView{
@ProjectionProperty("{ $childCollectionSize: '$childArray'}")
int childCollectionSize;
}