删除Mongo中的STRANGE集合

时间:2015-04-13 09:58:40

标签: mongodb collections

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


更新

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

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

UPDATE2:

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

1 个答案:

答案 0 :(得分:3)

我无法确切地告诉你你到底是怎么做到的,但发生的事情是你已经真正创建了一个名为[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()
相关问题