代码之家  ›  专栏  ›  技术社区  ›  Ankit Kumar

如何在mongodb中过滤至少6个月的数据?

  •  1
  • Ankit Kumar  · 技术社区  · 1 年前

    我想在MongoDB中获取从当前日期起最近6个月的用户数据。我是按状态过滤数据,而不是得到数组的响应。我还想根据日期应用另一个查询。我想根据最近6个月过滤一次,然后根据当前日期后的最近30天在另一个查询中过滤。 我的数据是-

      {
        _id: new ObjectId("63ac23187dc7d"),
        details: 'hii there i am feeling great today',
        status: '1',
        createdAt: 2021-11-28T11:06:00.736Z
      },
      {
        _id: new ObjectId("63ac23b357dc96"),
        details: 'hi i am feeling good today',
        status: '1',
        createdAt: 2022-12-28T11:08:40.400Z,
      },
      {
        _id: new ObjectId("63b2b2afa0d8e"),
        details: 'Hello!! This is Ankit and feeling good',
        status: '1',
        createdAt: 2022-11-14T10:31:36.098Z
      },
      {
        _id: new ObjectId("63b2b2sswa0d91"),
        details: 'Felling bad a bit',
        status: '1',
        createdAt: 2023-01-02T10:32:27.149Z
      },
      {
        _id: new ObjectId("63b2b2a0d94"),
        details: 'Hmm, its ok ok',
        status: '1',
        createdAt: 2023-01-02T10:33:19.386Z
      }
    
    1 回复  |  直到 1 年前
        1
  •  1
  •   Junot    1 年前

    我们使用$gte查询运算符和JavaScript的Date.now()函数来检索日期大于或等于当前日期前6个月的所有订单文档。我们将使用JavaScript的新Date()获取当前日期,并使用setMonth()方法返回6个月。

    你可以试试这个

    let sixMonths = new Date();
    sixMonths.setMonth(sixMonths.getMonth() - 6);
    
    db.collections.find({ createdAt: { $gte: sixMonths } });
    

    对于这些天,你可以用“1”代替“6”,这相当于1个月。