【问题标题】:Remove STRANGE collection in Mongo在 Mongo 中删除 STRANGE 集合
【发布时间】:2015-06-18 14:25:40
【问题描述】:

我有一个带有一些集合的 MongoDB。在我的实际收藏中输入show collections 时,我看到了神秘的[object Object] 收藏。我无法使用或删除它,因为它的名称中有坏字符。 有人能解释一下是什么导致这个“集合”出现以及如何删除它吗?


更新:

db.getCollectionNames() 返回相同的结果:

[ "[object Object]", "my_collection", "system.indexes", "my_collection1" ]

更新2:

db.getCollection("[object Object]").drop() 工作。这种错误的原因仍然未知

【问题讨论】:

  • Can not delete collection from mongodb 的可能副本。至于怎么会出现,我真的不知道。
  • ...这样的集合存在的事实听起来像是一个错误。 db.getCollectionNames() 的输出有什么不同吗?
  • 在哪个数据库下显示这个集合?
  • @mnemosyn,已更新。对,似乎是一个错误,但遗憾的是我没有注意到是什么查询产生的
  • 我在解决这个问题时获得了一点乐趣——正如最后提到的,可能值得在 MongoDB jira 中为它创建一张票,以至少在发生这种情况时发出警告

标签: mongodb collections


【解决方案1】:

我不能确切地告诉你你是如何走到这一步的,但实际上你已经创建了一个名为[object Object] 的集合。这有点做作,但您可以通过以下方式重现您的情况:

// create an object, let's call it y
> var y = {a : 1, b : 2, c : [1, 2, 3]}
// now create a collection using the variable as the name by inserting
> db[y].insert({s : 1})
// we now have [object Object] as a collection
> show collections
ObjectId("552b9e7d8c5b893bc6bfae45")
[object Object]
system.indexes
// This makes it a little more obvious what we have done
> db.getCollection( "system.namespaces" ).find();
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\")" }
{ "name" : "x.system.indexes" }
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\").$_id_" }
{ "name" : "x.[object Object]" }
{ "name" : "x.[object Object].$_id_" }
// We can even query it
> db[y].find()
{ "_id" : ObjectId("552b9f728c5b893bc6bfae47"), "s" : 1 }
// To make it even more obvious what is going on, let's use a different object
> var z = {a : 1, b : 2, c : [1, 2, 3, 4]}
> db[z].insert({t : 1})
// BUT, no new collection this time, we still just have one [object Object]
> db.getCollection( "system.namespaces" ).find();
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\")" }
{ "name" : "x.system.indexes" }
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\").$_id_" }
{ "name" : "x.[object Object]" }
{ "name" : "x.[object Object].$_id_" }
// let's confirm by querying
db[z].find()
{ "_id" : ObjectId("552b9f728c5b893bc6bfae47"), "s" : 1 }
{ "_id" : ObjectId("552ba1888c5b893bc6bfae48"), "t" : 1 }

因此,MongoDB 允许使用 Object 创建一个集合,但无论您传入哪个对象,所有对象都会评估为相同的 [object Object] 字符串。这意味着您无法确定自己是如何做到的创建这个集合,但从好的方面来说,这也意味着您需要做的就是创建任何对象,您可以使用它来删除它。就我而言,我将只重用上面的 z 变量,但您基本上可以使用任何对象来进行删除:

> db[z].drop()
true
> db.getCollection( "system.namespaces" ).find();
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\")" }
{ "name" : "x.system.indexes" }
{ "name" : "x.ObjectId(\"552b9e7d8c5b893bc6bfae45\").$_id_" }

你有它,它消失了。至于这是否是一个错误,你可以说[object Object] 是一个有效的集合名称——我不建议使用它,但这并不违法。所以也许不是一个错误,而是一个可以提出的改进。

顺便说一句,我测试了你甚至不必在这里实际使用对象,你可以用字符串来做,像这样:

var j = '[object Object]'
db[j].drop()

【讨论】:

    猜你喜欢
    • 2021-01-09
    • 2013-12-11
    • 2014-10-10
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多