根据“时间"从MongoDB集合中删除文档.日期字段的

问题描述:

我有一个集合,该集合存储具有以下结构的文档:

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"), 
}

我要删除所有带有特定"Id"和"Type"的文档,其中"InDate"字段的时间为18:30: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?

正则表达式不适用于非字符串的内容.实际上,没有简单的方法可以通过普通查询表达式中的时间值来选择BSON Date.

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.

为此,您需要提供 $where 条件,并具有附加的逻辑以仅在日期值的时间部分进行匹配.

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
  }
})

当然,这只是提供的数据中的第一个文档,尽管它实际上只是由"Id"标识的,因为该值在两者之间是唯一的.

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.

.getUTCHours() .getUTCMinutes() 是JavaScript Date 对象方法,是在 $where href ="https://docs.mongodb.com/manual/reference/operator/query/where/" rel ="nofollow noreferrer"> $where 表达式.

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

通常,MongoDB 3.6(在撰写本文时即将推出)比

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] } 
      ] 
    }   
  }}
])

但是,此类表达式不能直接与 .remove() .deleteMany() ,但是 $where 表达式可以.

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