0

I have a structure where i keep history of values (past, and can be in the future) for some fields similar to this:

[
    {
        "_id": 1,
        "name": "Product 1",
        "priceHistory":
            [
                {
                    "startDate": ISODate("1970-01-01T00:00:00.000Z"),
                    "value": 1200,
                },
                {
                    "startDate": ISODate("2020-01-20T00:00:00.000Z"),
                    "value": 100,
                }
            ]
    },
    {
        "_id": 2,
        "name": "Product 2",
        "priceHistory":
            [
                {
                    "startDate": ISODate("1970-01-01T00:00:00.000Z"),
                    "value": 500,
                },
                {
                    "startDate": ISODate("2020-01-20T00:00:00.000Z"),
                    "value": 300,
                },
                {
                    "startDate": ISODate("2021-01-01T00:00:00.000Z"),
                    "value": 500,
                }
            ]
    },
]

Can I write a query so that I can get all products that have the price 300 at a given date?

The reason why I cant have "currentPrice" field is because you can schedule a price change, and I want to avoid having a daemon that changes that field when the scheduled date comes, especially since I have a lot of fields, and a lot of record that would need updating, so the update process would take a lot of time.

spiroski
  • 629
  • 2
  • 11
  • 16
  • 1
    Does this answer your question? [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) As suggested over there you need to use `$elemMatch`, if you wanted to get just the matching element from array use `$filter` – whoami - fakeFaceTrueSoul Jun 24 '20 at 18:33
  • 1
    Yes, $elemMatch will help me achieve what I want. In addition, I will add endDate to each historical item in the array, and that way I can search with $elemMatch for the items that have startDate <= chosenDate && endDate >= chosenDate. Thank you. – spiroski Jun 26 '20 at 15:44

0 Answers0