【问题标题】:Deleting documents in mongo collection with _id attribute of a given BSON type使用给定 BSON 类型的 _id 属性删除 mongo 集合中的文档
【发布时间】:2016-03-17 10:31:33
【问题描述】:

我有一个集合,其中每个文档的_id 都是字符串类型。由于一些问题,我们插入了一些ObjectId类型的_id错误的文档。

{
  "_id": "M123",
  "title": "Test",
  ...
}
{
  "_id": ObjectId("566de977e4b075b86383b629"),
  "title": "Test",
  ...
}

现在我想删除所有与第二个类似的文档。有没有办法将此查询指定给db.Collection1.remove()

我尝试在谷歌上搜索,在那里我找到了指定特定字段值而不是其类型的条件的查询。

【问题讨论】:

  • $type
  • 我尝试了以下查询。 db.Collection1.find({"_id":{$type:"objectId"}}).count() 2016-03-17T16:26:25.271+0530 E QUERY Error: count failed: { "code" : 10061, "ok" : 0, "errmsg" : "exception: type not supported for appendMinElementForType" } 在 DBQuery.count (src/mongo/shell/query.js:326:11) 的错误 () at (shell) :1:44 在 src/mongo/shell/query.js:326
  • "alias" 值仅在 MongoDB 3.2 中受支持。 所有 版本都使用数值。例如,只查找 BSON 类型为“字符串”db.Album.find({ "_id": { "$type": 2 } })_id,这在数字上当然是 BSON 类型 2
  • 感谢@BlakesSeven 我可以使用查询'db.Collection1.remove({"_id":{$type: 7}})'删除文档

标签: mongodb removeall


【解决方案1】:

我可以使用以下查询删除具有 ObjectId 类型的 _id 的行。

db.Collection1.remove({"_id":{$type: 7}})

这适用于 3.0 之前的旧版本的 mongo 对于较新的版本,您还可以使用

db.Collection1.remove({"_id":{$type: "objectId"}})

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 2021-02-22
    • 2016-03-28
    • 2020-05-02
    • 2011-03-26
    • 1970-01-01
    相关资源
    最近更新 更多