【问题标题】:Mongo client can't access collections prefixed with an underscoreMongo 客户端无法访问带有下划线前缀的集合
【发布时间】:2014-06-19 14:56:04
【问题描述】:

我在 Mongo 中用下划线命名了一个集合,但无法从 shell 访问它:

meteor:PRIMARY> show collections
_assignments
chatmessages
(... other stuff)

尝试在第一个集合上运行任何函数都会导致错误:

meteor:PRIMARY> db._assignments.find()
Thu Jun 19 10:53:28.450 TypeError: Cannot call method 'find' of undefined

但是,其他集合工作正常:

meteor:PRIMARY> db.chatmessages.find()
{ "room" : "j5oau9DJ6GNpT9nR8", "userId" : "at9Kt8NNL4aeof6LE", "text" : "@nomad943 can you take a look at event #1?", "timestamp" : 1391806611977, "_id" : "26GbXa6c4B65FYRxC" }
{ "room" : "T7JfjBhri48bNHAfQ", "userId" : "B82LxmPBZWDnN4N2p", "text" : "Thinking #60 should be deleted, it's a duplicate of #36 and the region is wrong for the province", "timestamp" : ISODate("2014-06-18T18:57:56.480Z"), "_id" : "29pKqPhi4hgxCb2Ky" }

这是怎么回事?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    除了 shell 无法使用它的默认帮助程序语法解决此问题外,我没有看到其他问题。你仍然可以在 shell 中访问这样命名的集合:

    db.createCollection("_assignments")
    { "ok" : 1 }
    db.getCollection("_assignments").find()
    db.getCollection("_assignments").insert({ "a": 1 })
    WriteResult({ "nInserted" : 1 })
    db.getCollection("_assignments").find({ "a": 1 })
    { "_id" : ObjectId("53a36a4047234c4e9bb4feac"), "a" : 1 }
    

    【讨论】:

      【解决方案2】:

      这是一个已知的错误。不要在集合前加上下划线。

      https://jira.mongodb.org/browse/SERVER-445

      【讨论】:

      • 我什至没有使用那个集合,我只想放弃它。可能吗?
      • 使用 robomongo 之类的工具。我刚刚尝试了您的方案,并且以 _ 为前缀的 mongo 集合在流星和 robomongo 中都可以正常工作。我无法到达它的唯一方法是通过 mongo 控制台
      • @marcodejongh 您可以在 mongo shell 中使用这些集合,而不是直接使用助手。请改用正确的方法。
      【解决方案3】:

      当集合名称以下划线开头时,它必须用双引号引起来。它表明(至少在 MongoDB 版本 4.x 或更低版本中)下划线(_ 作为第一个字符)没有得到正确解释,因此您必须将其括在引号中(即指定为纯字符串),例如以下不会工作:

      db._someCollection.find()
      

      但以下工作正常:

      db.getCollection("_someCollection").find();
      

      HTH

      【讨论】:

        【解决方案4】:

        如果您的集合名称包含下划线并且您想要插入一个新文档,您必须将集合分配给一个变量并将其用于插入,如下所示:

        var assignments = db.getCollection("_assignments")
        
        assignments.insertOne(
           {
              room : "123",
              userId : "1",
              text : "text"
           }
        )
        

        documentation之后。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-08
          • 2011-08-24
          • 2017-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多