MongoEngine: Limiting number of responses from DBRef

834 Views Asked by At

I have a document with around 7k DBRefs in one field to other objects. I want to limit the number of the objects coming back when I query the DBRef field but I cannot find an obvious way of doing it.

project = Project.objects.find({'id': 1})
users = project.users[:10]

On line 2 MongoEngine performs a query to retrieve ALL the users not just the first 10. What can I do to limit the query to only retrieve the first 10?

2

There are 2 best solutions below

2
On BEST ANSWER

users = project.users[:10],

This operation is a client side operation, which is performed on the users array that has all the 7k DBRefs values returned by mongodb.

What can I do to limit the query to only retrieve the first 10?

You need to include a projection operation to just select the first 10 elements in the users array.

Project.objects.find({"id": 1},{"users":{"$slice":10}})

The syntax in MongoEngine:

Project.objects(id=1).fields(slice__users[0,10])
0
On

If I understand you correctly, there is no way to return a portion of one field. You can pick and choose what fields you are returning, but there is no way to specify a portion of one field.