Remove documents from a MongoDB collection based on “time” of a Date field

本小妞迷上赌 提交于 2019-12-11 16:02:57

问题


I have a collection which stores documents with the following structure:

{ 
    "_id" : NumberLong(-6225637853094968071), 
    "Id" : "1585534", 
    "Type" : NumberInt(42), 
    "InDate" : ISODate("2017-10-05T18:30:00.000+0000"), 
}
{ 
    "_id" : NumberLong(-622563784353458071), 
    "Id" : "15832422", 
    "Type" : NumberInt(42), 
    "InDate" : ISODate("2017-10-06T00:00:00.000+0000"), 
}

I want to delete all documents with a particular "Id" and "Type" where the "InDate" field has time 18:30:00.000+0000. I tried using this query:

 db.collection.remove({
"ChannelType": NumberInt(28),
"HotelId": "1585534",
"CheckInDate": /$18:30:00.000+0000/
})

but it doesnt work. How to do this?


回答1:


A Regular Expression will not work on something that is not a string. There actually is no simple way of selecting a BSON Date by purely it's time value in a regular query expression.

In order to do this you would supply a $where condition with the additional logic to match on just the time portion of the date value.

Based on the data actually supplied in the question:

db.getCollection('collection').remove({
  "Id": "1585534",
  "Type": NumberInt(42),
  "$where": function() {
    return this.InDate.getUTCHours() === 18
      && this.InDate.getUTCMinutes() === 30
  }
})

Which is of course just the first document in the provided data, even though it's really just identified by "Id" anyway since that value is unique between the two.

The .getUTCHours() and .getUTCMinutes() are JavaScript Date object methods, which is how a BSON Date is expressed when used within a $where expression.


Trivially, MongoDB 3.6 ( upcoming as of writing ) allows a more efficient form than $where in aggregation expressions:

db.getCollection('collection').aggregate([
  { "$match": {
    "Id": "1585534",
    "Type": NumberInt(42),
    "$expr": {
      "$and": [
        { "$eq": [{ "$hour": "$InDate" }, 18 ] },
        { "$eq": [{ "$minute": "$InDate" }, 30] } 
      ] 
    }   
  }}
])

However such expressions cannot be used directly with methods such as .remove() or .deleteMany(), but $where expressions can.




回答2:


Iso date don't match a string, you need to use isodate in the query too

db.collection.remove({
    "ChannelType": NumberInt(28),
    "HotelId": "1585534",
    "InDate": ISODate(2017-10-05T18:30:00.000+0000)
})


来源:https://stackoverflow.com/questions/46704035/remove-documents-from-a-mongodb-collection-based-on-time-of-a-date-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!