0
我在我的mongo集合中有以下數據。使用聚合框架將SQL查詢轉換爲mongo
db.tempTest.insert([{
"id" : "12345",
createdOn : ISODate("2016-09-15T19:25:00.000Z"),
"addr" : "address1",
"book" : "book1"
}, {
"id" : "12345",
createdOn : ISODate("2016-09-14T19:25:00.000Z"),
"addr" : "address2",
"book" : "book2"
}, {
"id" : "12346",
createdOn : ISODate("2016-09-15T19:26:00.000Z"),
"addr" : "address3",
"book" : "book3"
}, {
"id" : "12346",
createdOn : ISODate("2016-09-15T19:26:01.000Z"),
"addr" : "address4",
"book" : "book4"
}, {
"id" : "12346",
createdOn : ISODate("2016-09-14T19:26:01.000Z"),
"addr" : "address5",
"book" : "book5"
}, {
"id" : "12347",
createdOn : ISODate("2016-09-14T19:26:01.000Z"),
"addr" : "address6",
"book" : "book6"
}, {
"id" : "12347",
createdOn : ISODate("2016-09-10T19:26:01.000Z"),
"addr" : "address7",
"book" : "book7"
}, {
"id" : "12345",
createdOn : ISODate("2016-09-14T19:25:00.000Z"),
"addr" : "address8",
"book" : "book8"
}]);
查詢相應的Postgres到SQL將如下:
SELECT *
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY idnew ORDER BY createdOn ASC) AS rownumber,
*
FROM temp) AS TEMP
WHERE
rownumber = 1
AND idnew IN ('12345', '12346', '12347')
ORDER BY
createdOn ASC
我是新來蒙戈分貝。我通過了聚合框架並能夠使用$匹配,但無法使用$ group從idnew組中獲取最少createdOn的文檔。我需要所有符合條件的文件字段。 請幫忙構建mongo shell的查詢。
結果集應如下:
{
"id" : "12347",
createdOn : ISODate("2016-09-10T19:26:01.000Z"),
"addr" : "address7",
"book" : "book7"
}, {
"id" : "12345",
createdOn : ISODate("2016-09-14T19:25:00.000Z"),
"addr" : "address8",
"book" : "book8"
}, {
"id" : "12346",
createdOn : ISODate("2016-09-14T19:26:01.000Z"),
"addr" : "address5",
"book" : "book5"
}
隨着大量的搜索和試驗,我可以設法提取數據 但是當使用$ arrayElemAt函數格式得到改變。以下共享 查詢。 請幫我將此輸出轉換爲上面共享的輸出。
db.tempTest.aggregate(
[
{$sort : {createdOn:1}},
{ $group : { _id : "$id", details: { $push: "$$ROOT" } } },
{$project:
{
details: { $arrayElemAt: [ "$details", 0 ] }
}
}
]
)
截至目前,輸出顯示爲:
/* 1 */
{
"_id" : "12347",
"details" : {
"_id" : ObjectId("57dc1b094c105db1a666b0a8"),
"id" : "12347",
"createdOn" : ISODate("2016-09-10T19:26:01.000Z"),
"addr" : "address7",
"book" : "book7"
}
}
/* 2 */
{
"_id" : "12345",
"details" : {
"_id" : ObjectId("57dc1b094c105db1a666b0a3"),
"id" : "12345",
"createdOn" : ISODate("2016-09-14T19:25:00.000Z"),
"addr" : "address2",
"book" : "book2"
}
}
/* 3 */
{
"_id" : "12346",
"details" : {
"_id" : ObjectId("57dc1b094c105db1a666b0a6"),
"id" : "12346",
"createdOn" : ISODate("2016-09-14T19:26:01.000Z"),
"addr" : "address5",
"book" : "book5"
}
}