已删除具有相同字段的mongodb文档

hgncfbus  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(168)

我有一个调度程序在我的服务器上运行,并生成一个列表的药物没有签署每天,这个问题有时会发生,而解决这个问题,我想创建一个脚本检查和删除这些重复的项目生成.感谢您的帮助.

此处为生成的一些样本日期:我想检查匹配字段[药物、时间、日期],并仅返回1份文件,然后删除所有重复项。

[
  {
    "_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"
  }
]

预期输出:(注意:时间和日期不同)

[
  {
    "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"
  },
]

这里MongodbPlayground显示结果-〉Mongodb Playground

ryevplcw

ryevplcw1#

希望这个回答对大家有帮助
注意:-您的日期在每个对象中并不相同,因此您的预期输出可能是错误的
我已经附上了代码为. https://mongoplayground.net/p/hYrgPd7od02的Playground网址

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        med: "$med",
        Time: "$Time",
        Date: "$Date",
        
      },
      "med": {
        "$first": "$med"
      },
      "Time": {
        "$first": "$Time"
      },
      "Date": {
        "$first": "Date"
      }
    }
  },
  {
    "$project": {
      _id: 0
    }
  }
])

相关问题