mongo相当于sql查询

时间:2015-10-23 11:44:15

标签: mongodb aggregation-framework

我需要构建一个mongo查询来从一个集合中获取结果,该集合具有与以下sql相同的结构。

click for picture of table structure

我的SQL查询:

"123456789" =~ /$_/

结果如下所示

SELECT * FROM (
  SELECT
    db.date,
    db.points,
    db.type,
    db.name,
    db.rank,
    YEARWEEK( db.date ) AS year_week
  FROM _MyDatabase db
  WHERE
    db.personId = 100 AND
    db.date BETWEEN '2012-10-01' AND '2015-09-30'
  ORDER BY
    YEARWEEK( db.date ),
    db.type,
    db.points DESC
  ) x
GROUP BY
  x.year_week DESC,
  x.type;

到目前为止,我尝试过不同的群组/聚合查询,但我无法获得类似的结果。希望你们中的一个人拥有比我更多的mongo经验,并且可以给我一个如何解决这个问题的提示。

1 个答案:

答案 0 :(得分:0)

你会想要这样的东西:

var start = new Date(2012, 9, 1),
    end = new Date(2015, 8, 30),
    pipeline = [
        {
            "$match": {
                "personId": 100,
                "date": { "$gte": start, "$lte": end }
            }
        },
        {
            "$project": {
                "date": 1, "points": 1, "type": 1, "name": 1, "rank": 1,
                "year_week": { "$week": "$date" }
            }
        },
        {
            "$sort": {
                "year_week": 1, 
                "type": 1,
                "points": -1
            }
        },
        {
            "$group": {
                "_id": {
                    "year_week": "$year_week", 
                    "type": "$type"
                }
            }
        }
    ];
db.getCollection("_MyDatabase").aggregate(pipeline);