I have a scheduler running on my server and generating a list of medications that didn't sign every day, this problem occurs sometimes and while solving this issue I want to create a script checking and deleting those duplicate items generated. Appreciate your help.
Here some sample date generated : I want to check matched field [med, time, date] and return only 1 document then removed all duplicates.
[
{
"_id": ObjectId("6375ea026a0b4e0015d80f77"),
"med": ObjectId("610845e7f5b0e00017754d50"),
"Time": "8:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
{
"_id": ObjectId("6375ea026a0b4e0015d80fd4"),
"med": ObjectId("61f988e82cf5760018113cee"),
"Time": "7:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
{
"_id": ObjectId("6375ea026a0b4e0015d80fdd"),
"med": ObjectId("62d1c6e93603ed00177812ee"),
"Time": "6:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
{
"_id": ObjectId("6375ea02304a870015dfa2ec"),
"med": ObjectId("610845e7f5b0e00017754d50"),
"Time": "8:00am",
"Date": "2022-11-16T08:00:00.005 0000"
},
{
"_id": ObjectId("6375ea02304a870015dfa349"),
"med": ObjectId("61f988e82cf5760018113cee"),
"Time": "7:00am",
"Date": "2022-11-16T08:00:00.005 0000"
},
{
"_id": ObjectId("6375ea02304a870015dfa352"),
"med": ObjectId("62d1c6e93603ed00177812ee"),
"Time": "6:00am",
"Date": "2022-11-16T08:00:00.005 0000"
}
]
Expected output: (Note: Time and Date are different)
[
{
"med": ObjectId("610845e7f5b0e00017754d50"),
"Time": "8:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
{
"med": ObjectId("61f988e82cf5760018113cee"),
"Time": "7:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
{
"med": ObjectId("62d1c6e93603ed00177812ee"),
"Time": "6:00am",
"Date": "2022-11-16T08:00:00.008 0000"
},
]
Here Mongodb Playground for displaying result -> Mongodb Playground
CodePudding user response:
Hope this answer will helpful
Note:- Your date is not same in every object so may be your expected output is wrong
i have attached playground url with code. https://mongoplayground.net/p/hYrgPd7od02
db.collection.aggregate([
{
"$group": {
"_id": {
med: "$med",
Time: "$Time",
Date: "$Date",
},
"med": {
"$first": "$med"
},
"Time": {
"$first": "$Time"
},
"Date": {
"$first": "Date"
}
}
},
{
"$project": {
_id: 0
}
}
])