mongodb - 将文档插入到 MongoDB 中的特定 ID

标签 mongodb

我正在尝试将文档插入到特定 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/

相关文章:

node.js - Mongoose 使用 $lookup 包含辅助文档中的字段

java - 为什么 MongoDB Java API 的更新插入如此慢?

MongoDB:按键迭代集合?

mongodb - Ansible - 在 wait_for 时重复任务

Node.js 生成随机唯一 id 并通过 Do .. While 循环检查 mongoDB 是否存在

c# - MongoDB 中的正则表达式 + 选项(C# 驱动程序)

mongodb - 排序聚合 addToSet 结果

node.js - 在带有 Socket.io 的 MongoDB 中使用 Change Stream 时, 'change' 被多次触发

Mongodb - 如何在多个字段中查找字符串?

node.js - 使用 NODEJS 保存到 Mongodb 后如何获得响应