Get the last document and filter nested array

152 Views Asked by At

First time playing with MongoDB (and pymongo) and I have the documents below.
I'm trying to make the following query:

  1. get the top 1 entry, ordered by time_added descending
  2. from that subset of documents (let's call it entries.stocks), get the stocks that price is less than a balance value
  3. order by volume and price in that order.

From what I've googled it seems this can be done with aggregation but I only managed to do the first step with:
db.entries.find().sort('date_added', -1).limit(1)

Documents:

[
  {
    "_id": {
      "$oid": "5fcd2582a7a12288df9a6bf3"
    },
    "stocks": [
      {
        "name": "stock_name",
        "volume": 73,
        "price": 135
      },
      {
        "name": "stock_name",
        "volume": 44,
        "price": 324
      }
    ],
    "date_added": {
      "$date": "2020-12-06T18:40:02.000Z"
    }
  },
  {
    "_id": {
      "$oid": "5fcd2582a7a12288df9a6ad0"
    },
    "stocks": [
      {
        "name": "stock_name",
        "volume": 342,
        "price": 43
      },
      {
        "name": "stock_name",
        "volume": 544,
        "price": 66
      }
    ],
    "date_added": {
      "$date": "2020-12-05T18:40:02.000Z"
    }
  }
]
0

There are 0 best solutions below