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(
        "5f687ba6a93aeddc476ea157"
      ),
    },
  },
  {
    $filter: {
      input:
        "$messages",
      as: "message",
      cond: {
        $gte: [
          "$$message.send_at",
          new Date(
            "2020-10-12T13:00:00.000Z"
          ),
        ],
      },
    },
  },
];

deep dive subcollections#

https://gist.github.com/MonksterFX/c06e8fdeaa577760a325424ed3a84bd6

http://www.petecorey.com/blog/2020/01/29/mongodb-object-array-lookup-aggregation/

further reading#