2014-04-18 229 views
2

這是來自MongoDB。MongoDB插入問題

我正在關注this tutorial

我有收集如下圖所示:

$ show collections 
mycol 
mycollection 
system.indexes 
test 
tutorialspoint 

然後,當我試圖到集合中插入一條記錄,使用下面的語法,我得到的錯誤:

2014-04-18T08:03:55.168-0400 SyntaxError: Unexpected token ILLEGAL 

db.mycol.insert({ 
    _id: ObjectId(7df78ad8902c), 
    title: 'MongoDB Overview', 
    description: 'MongoDB is no sql database', 
    by: 'tutorials point', 
    url: 'http://www.tutorialspoint.com', 
    tags: ['mongodb', 'database', 'NoSQL'], 
    likes: 100 
}) 

以下是來自mongodb的複製/粘貼

db.mycol.insert({ 
... _id: ObjectId(7df78ad8902c), 
... title: 'MongoDB Overview', 
... description: 'MongoDB is no sql database', 
... by: 'tutorials point', 
... url: 'http://www.tutorialspoint.com', 
... tags: ['mongodb', 'database', 'NoSQL'], 
... likes: 100 
... }) 
2014-04-18T08:03:55.168-0400 SyntaxError: Unexpected token ILLEGAL 
+0

該示例存在缺陷,因爲ObjectId(7df78ad8902c)不是有效的JavaScript。 – JohnnyHK

回答

2

嘗試使用不帶_id字段的插入。這是由Mongodb自動生成的。

像這樣:

db.mycol.insert({ 
     title: 'MongoDBOverview', 
     description: 'MongoDBisnosqldatabase', 
     by: 'tutorialspoint', 
     url: 'http: //www.tutorialspoint.com', 
     tags: [ 
      'mongodb', 
      'database', 
      'NoSQL' 
     ], 
     likes: 100 
    }); 

如果你想使用_id領域:
MongoDB的文檔:Insert a document using the _id field

例:_id: 10

The value of _id must be unique within the collection to avoid duplicate key error.

+0

不使用__id字段爲我工作 – mujaffars

0

的值需要加引號。另外,示例中的字符串長度不正確。插入某些內容而不指定_id字段,然後執行db.mycol.find()以查看正確的格式。根據文檔,該字段爲12個字節。 24個字符的字符串使用每個字節2個十六進制字符。 (注意:我也是mongoDB noob,所以我確信這個答案可能存在缺陷。)