删除 Mongo 中的 STRANGE collection

Remove STRANGE collection in Mongo

我有一个 MongoDB 和一些 collection。当沿着我实际的 collection 键入 show collections 时,我看到了神秘的 [object Object] collection。我无法使用或删除它,因为它的名称中包含错误字符。 谁能解释一下是什么原因导致 "collection" 出现以及如何删除它?


更新:

db.getCollectionNames() returns 同样的结果:

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

更新2:

db.getCollection("[object Object]").drop() 有效。出现这种bug的原因还不清楚

我无法确切地告诉您您是如何走到这一步的,但实际情况是您确实创建了一个名为 [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] 字符串,无论您传入的是什么对象。这意味着您可以'不太确定您是如何设法创建这个集合的,但从好的方面来说,这也意味着您需要做的就是创建任何对象,然后您可以使用它来删除它。对于我的情况,我将重新使用上面的 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()