我已经回答了这个问题:
db.coll1.aggregate([
{
$match:{
$or:[
{time:{$lt:145941000},code:413}
,{time:{$lt:145942000},code:415}
]
}
}
,{ $sort:{time:-1}}
,{ $group:{_id:"$code"
,lastMatch:{$first:"$price"}
}
}
])
这是下面的集合:
我想这样查询:
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
...
如何查询mongodb? 我知道如何查询,但似乎mongodb的聚合不能'联合'
db.m20170705.aggregate([
{
$match:{code:1
,time:{$lte:145940500}
}
}
,{$sort:{time:-1}}
,{$limit:1}
])
union ????
答案 0 :(得分:0)
在不知道mongodb(但知道SQL)的情况下,我会说ORDER BY
不属于SELECT
中UNION
的一部分,因此必须放置一次最后。
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
在这种情况下的工作方式不同,必须以其他方式实现,例如在子选择内部(如果在MongoDB中可用)
答案 1 :(得分:0)
您可以参考:https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/
样品:
table1.aggregate([
{
"$match":
{
"$code": 2
}
},
{
"$project":
{
"$code": 1,
"$price": 1
}
},
{
"$limit": 1
}
])