How can I publish only a subset of an array in a document?

I have a collections with document that have the following pattern:

{
    "name": "jononomo",
    "books_read": ["book one", "book two", "book three", ... "book eight hundred and fifty four", "book eight hundred and fifty five", etc...]
}

I would like to publish all documents in this collection, but because the arrays are so long, I only want to send over that last three or four items in the array. Is this possible?

Thanks.

Use the Mongo $slice operator. So update your publish function to use something like:

return SomeCollection.find({ 
  _id: 'someid' 
}, { 
  fields: { 
    'books_read': { 
      $slice: -3 
    }
  }
});

Note that minimongo doesn’t fully support the $slice operator. You should be able to use it in your publish function, but not client side.

2 Likes

Thanks - I guess I actually want the array items that match a recent date criteria, regardless of where they are in the array. Is that possible?

This might help: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

Thanks. I looked into it, but I don’t think $elemMatch does what I need. Screenshot from the docs attached.

1 Like