mongo snippets: arrays

extract only subset of embedded documents#

Sometimes we want to extract not all embedded documents from a matched documents. Imagine a object chatroom:

    _id: ObjectId('5f687ba6a93aeddc476ea157'),
    messages: Array<Messages>

The messages look like this:

    sender: Reference,
    send_at: Date
    payload: ""

Now when we want to extract all message before, after a date we could query the Chatroom and filter it in the backend logic, or we can use Aggregation Pipeline. In this specifc case we have two steps in the pipeline:

  • find chatroom (match)
  • extract all Messages before/after a date in the chatroom (filter)

the query#

Example for after a defined date:

    $match: {
      _id: new ObjectId(
    $filter: {
      as: "message",
      cond: {
        $gte: [
          new Date(

deep dive subcollections#

further reading#