1

I have resloved this question:

db.coll1.aggregate([
    {
        $match:{
            $or:[
                {time:{$lt:145941000},code:413}
                ,{time:{$lt:145942000},code:415}
            ]
        }
    }   
    ,{  $sort:{time:-1}}
    ,{  $group:{_id:"$code"
            ,lastMatch:{$first:"$price"}
        }
    }
])

This is the collection below:

collection

I want to query like this:

SELECT code, price FROM table1 WHERE code = 1 AND time<123xxx ORDER BY time desc LIMIT 1
UNION
SELECT code, price FROM table1 WHERE code = 2 AND time<24xxx ORDER BY time desc LIMIT 1
UNION
SELECT code, price FROM table1 WHERE code = 3 AND time<1xxx ORDER BY time desc LIMIT 1
UNION
...

How can I query mongodb like this? I know how query one but it seem that the aggregate of mongodb is not able to 'union'

db.m20170705.aggregate([
    {
        $match:{code:1
            ,time:{$lte:145940500}
        }
    }
    ,{$sort:{time:-1}}
    ,{$limit:1}
])
union ????
Li Da
  • 41
  • 4

2 Answers2

0

Without knowing mongodb (but knowing SQL), I would say ORDER BY is not part of the SELECTs in a UNION and thus has to be placed once at the end.

SELECT code, price FROM table1 WHERE code = 1 AND time<123xxx
UNION
SELECT code, price FROM table1 WHERE code = 2 AND time<24xxx
UNION
SELECT code, price FROM table1 WHERE code = 3 AND time<1xxx
UNION
...
ORDER BY time desc

(LIMIT works differently in this case, it has to be implemented otherwise, for example inside a subselect, if available in MongoDB)

Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
0

You can refer this: https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/

Sample:

table1.aggregate([
        {
            "$match":
                {
                    "$code": 2
                }
        },
        {
            "$project":
                {
                   "$code": 1,
                   "$price": 1
                }
        },
        {
            "$limit": 1
        }
])
sohamdodia
  • 357
  • 1
  • 4
  • 11