Amaresh HM
Amaresh HM

Reputation: 51

How to find difference between dates in different documents using Loopback 3 remote method in MongoDB?

Suppose my 2 documents are like this in mongodb. How do I find date difference between the fields "eventCreatedAt". I am using loopback 3 remote method implementation for this.

[
  {
    "eventType": "offer",
    "currentPrice": 3,
    "seller": "Medicalstudent",
    "buyer": "musiciann",
    "eventCreatedAt": "2022-03-09T10:25:20.308Z",
    "isExistingOffer": true,
    "timeDiffOfPreTran": 1,
    "id": "6228853556f56afb3d995d50",
    "nftId": "622880fc56f56afb3d995d4f"
  },
  {
    "eventType": "offer",
    "currentPrice": 5,
    "seller": "Medicalstudentss",
    "buyer": "music",
    "eventCreatedAt": "2022-03-09T10:25:20.308Z",
    "isExistingOffer": false,
    "timeDiffOfPreTran": 4,
    "id": "622f2d8e550a568093b54c93",
    "nftId": "622880fc56f56afb3d995d4f"
  }
]

Upvotes: 0

Views: 73

Answers (1)

YuTing
YuTing

Reputation: 6629

db.collection.aggregate([
  {
    $lookup: {
      from: "nft",
      localField: "nftId",
      foreignField: "nftId",
      as: "docs",
      pipeline: [
        {
          $setWindowFields: {
            partitionBy: "",
            sortBy: { eventCreatedAt: 1 },
            output: {
              shift: {
                $shift: {
                  output: "$eventCreatedAt",
                  by: -1,
                  default: "$$REMOVE"
                }
              }
            }
          }
        },
        {
          $set: {
            shift: {
              $dateDiff: {
                startDate: { $toDate: "$shift" },
                endDate: { $toDate: "$eventCreatedAt" },
                unit: "day"
              }
            }
          }
        }
      ]
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $setWindowFields: {
      partitionBy: "",
      sortBy: { eventCreatedAt: 1 },
      output: {
        shift: {
          $shift: {
            output: "$eventCreatedAt",
            by: -1,
            default: "$$REMOVE"
          }
        }
      }
    }
  },
  {
    $set: {
      shift: {
        $dateDiff: {
          startDate: { $toDate: "$shift" },
          endDate: { $toDate: "$eventCreatedAt" },
          unit: "day"
        }
      }
    }
  }
])

mongoplayground

Upvotes: 0

Related Questions