Mongo Db查询以获取不同的记录

时间:2020-08-04 06:11:07

标签: mongodb mongodb-query

我在数据库中的以下收藏大约有100万条记录。 hpw获得不同的eventID和eventName 从D中的集合中获取特定日期(例如29-07-2020)的信息?

{
    "_id" : 1814099,
    "eventId" : "LAS012",
    "eventName" : "CustomerTab",
    "timeStamp" : ISODate("2018-12-31T20:09:09.820Z"),
    "eventMethod" : "click",
    "resourceName" : "CustomerTab",
    "targetType" : "",
    "resourseUrl" : "",
    "operationName" : "",
    "functionStatus" : "",
    "results" : "",
    "pageId" : "CustomerPage",
    "ban" : "290824901",
    "jobId" : "87377713",
    "wrid" : "87377713",
    "jobType" : "IBJ7FXXS",
    "Uid" : "sc343x",
    "techRegion" : "W",
    "mgmtReportingFunction" : "N",
    "recordPublishIndicator" : "Y",
    "__v" : 0
}

1 个答案:

答案 0 :(得分:0)

例如,您可以使用distinct来获取唯一的eventID

let eventIds = await db.collection.distinct('eventID', {
   "timeStamp": {
         $gte: ISODate("2018-12-30T00:00:00.000Z"),
         $lt: ISODate("2018-12-31T00:00:00.000Z")
   }
})

如果要同时检索两个字段,则必须使用聚合:

db.collection.aggregate([
    {
        $match: {
            "timeStamp": {
                $gte: ISODate("2018-12-30T00:00:00.000Z"),
                $lt: ISODate("2018-12-31T00:00:00.000Z")
            }
        }
    },
    {
        $facet: {
            eventIds: [
                {
                    $group: {
                        _id: "$eventID"
                    }
                }
            ],
            eventName: [
                {
                    $group: {
                        _id: "$eventName"
                    }
                }
            ]
        }
    }
])

如果eventIDeventName彼此链接:

db.collection.aggregate([
    {
        $match: {
            "timeStamp": {
                $gte: ISODate("2018-12-30T00:00:00.000Z"),
                $lt: ISODate("2018-12-31T00:00:00.000Z")
            }
        }
    },
    {
        $group: {
            _id: {eventID: "$eventID", eventName: "$eventName"}
        }
    }
])