M
M
mmmq2021-02-02 18:13:29
Node.js
mmmq, 2021-02-02 18:13:29

How to request data from mongodb (mongoose) from a subdocument within the interval "from" and "to"?

Hello.

Tried different approaches with stackoverflow, can't return data range.

Document structure:

{
    symbol: "test",
    data: [{
            timestamp: 1,
            value: 10,
        },
        {
            timestamp: 2,
            value: 20,
        },
        {
            timestamp: 3,
            value: 30,
        },
        {
            timestamp: 4,
            value: 40,
        },
    ]
}


Request example:

function request(symbol, from, to) {
    return model.findOne({
        symbol,
        data: {
            $elemMatch: {
                timestamp: {
                    $gte: from,
                    $lt: to
                }
            }
        }
    }).then(res => res.data)
}

request('test', 2, 4)


As a result, it will return the entire array of data.

Can you tell me how to make the right request?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Cheremkhin, 2021-02-02
@Che603000

The return is correct. You have received a document that satisfies your request.
This document has array elements in the data field, where the timestamp is greater than 2 and less than 4. The
query returned the document as it is in the collection, the query does not filter the array, it uses the array elements for searching.
If you are going to filter the array then you can do it after query execution on the found documents.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question