1

Pretend I have this document:

{
    "name": "Bob",
    "friends": [
        "Alice",
        "Joe",
        "Phil"
    ],
    "posts": [
        12,
        15,
        55,
        61,
        525,
        515
    ]
}

All is good with only a handful of posts. However, let's say posts grows substantially (and gets to the point of 10K+ posts). A friend mentioned that I might be able to keep the array in order (i.e. the first entry is the ID of the newest post so I don't have to sort) and append new posts to the beginning. This way, I could get the first, say, 10 elements of the array to get the 10 newest items.

Is there a way to only retrieve posts n at a time? I don't need 10K posts being returned, when most of them won't even be looked at, but I still need to keep around for records.

2 Answers 2

3

You can use $slice operator of mongoDB in projection to get n elements from array like following:

db.collection.find({
   //add condition here
  }, {
    "posts": {
    $slice: 3 //set number of element here
      //negative number slices from end of array
    }
})
Sign up to request clarification or add additional context in comments.

Comments

-1

You can do this : create a list for posts you want to have (say you want first 3 posts) and return that list

for doc in db.collections.find({your query}):
    temp = ()
    for i in range (2):
        temp.push(doc['posts'][i])
    return temp

1 Comment

This will still do the big query to the DB

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.