MongoDB query for related records

I have a blog application. I need to make a MongoDB query (SQL is fine, I'll translate it), to get a specific post in the blog, and the immediate posts made before and after that post.

For instance, given this list of posts:

12/01/13 - Foo
15/01/13 - Bar
17/01/13 - Baz
27/01/13 - Taz

How do I write a query so that I get one of these, i.g Bar, and the immediate siblings Foo and Baz?

I'd like to do this without making three different queries to the database, for performance reasons.

In my application I fetch a single post like this:

model.findOne({
    date: {
        $gte: new Date(2013, 0, 15),
        $lt: new Date(2013, 0, 15, 24)
    },
    slug: 'Bar'
}, function(result){
    return { entry: result };
});

Here's one possibility (involving 2 queries, one to find the primary post, and the second to find the nearest doc):

  • Treat the data/posts as if it were a doubly-linked list.
  • You'll need to store reference IDs as links to the "previous" and "next" posts in each post document (array). This makes inserts a tiny more complex, but inserting a "new" blog post by date somewhere in the past seems unlikely.
  • Index the link field
  • Search for documents having the id of the primary document $in the link field