user3548853
user3548853

Reputation: 21

MongoDB Insert Issue

This is from MongoDB.

I am following this tutorial.

I have the collection as shown below:

$ show collections
mycol
mycollection
system.indexes
test
tutorialspoint

Then when I attempt to insert a record in to the collection, using the syntax below, I get the error:

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
})

Below is the copy/paste from 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

Upvotes: 2

Views: 1227

Answers (3)

K G
K G

Reputation: 69

The accepted commands are: insertOne() or insertMany()

db.mycol.insertOne({
_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

})

Upvotes: -1

John Carpenter
John Carpenter

Reputation: 11

The value needs to be in quotes. Also, the string in the example is the wrong length. Insert something without specifying the _id field, then do a db.mycol.find() to see the correct format. The field is 12 bytes according to the documentation. The 24-character string is using 2 hex characters per byte. (NOTE: I am also a mongoDB noob, so I am sure there may be flaws with this answer.)

Upvotes: 1

aludvigsen
aludvigsen

Reputation: 5991

Try the insert without the _id field. This is automatically generated by Mongodb.

Like this:

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

If you want to use the _id field:
Mongodb docs: Insert a document using the _id field

Ex: _id: 10

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

Upvotes: 2

Related Questions