我正在尝试将文档插入到特定 ID(由 mongoDB 默认生成的 ID)中,就像我们在 mysql 中所做的那样(INSERT WHERE id="985264")。
app.get('/', function(req , res){
db.facebook.insert({
_id:985264,
username: "Solomon.david",
status : "i love to code and eat",
comments: [
{
user : "jackson",
comment: "even me "
}
]
}, function(err,docs){
res.render('won.html');
});
});
最佳答案
您所要做的就是指定 _id
您尝试插入的文档中的属性:
db.collection.insert( { "_id": "unique_id", "foo": "bar", ... } )
如 the documentation 中所述,您应该注意执行一些注意事项 - 即,您需要确保
_id
您指定的是唯一的。取自链接的文档页面:
If the document does not specify an _id field, then MongoDB will add the _id field and assign a unique ObjectId for the document before inserting. Most drivers create an ObjectId and insert the _id field, but the mongod will create and populate the _id if the driver or application does not.
If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error.
关于mongodb - 将文档插入到 MongoDB 中的特定 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23593479/