![](/img/trans.png)
[英]How can I insert an array into my MongoDB stitch if I already have IDs defined?
[英]I am trying to iterate through an array of ids and insert a mongodb document if an id is not present. How can i get them to persist?
我正在使用Node JS和mongodb,并且我收集了ID范围为1-5000的文档。 但是,缺少一些ID,我希望每个文档都有一个ID。
这是我正在使用的代码:
MongoClient.connect("mongodb://localhost:27017/test", function(err, db) {
if(err) {
console.log("Unable to connect", err);
return;
}
console.log("We are connected");
var collection = db.collection('examples');
collection.aggregate(
[
{"$sort": {"user_id": 1} },
{"$out": "users"}
]
).toArray(function(err, docs) {
var toSave = [];
db.collection('users').find().toArray(function(err, docs){
docs.forEach(function(doc){
toSave.push(doc.user_id);
})
for (var i = 1; i < 5000; i++) {
if (toSave.indexOf(i) == -1) {
db.collection('examples').insert({
user_id: i,
create_dt: new Date()
})
}
}
console.log(toSave);
db.close()
})
});
});
我希望这可以通过我的toSave数组并为每个缺少的user_id插入文档,但是当我检查数据库时,它只能创建一个文档。
如何获取所有要保存在数据库中的文档?
我同意@Blakes。 在我看来,您确实想找到包含必须更新的user_id字段的文档,然后使用一些适当的值来更新该字段。 例如,user_id字段可能为null,或者它包含重复的值。 假设您有两个文档,每个文档的user_id为81:
{ "_id" : ObjectId("56c519bac62ffdbd22b000fd"), "user_id" : 81, "stuff" : 11 }
{ "_id" : ObjectId("56c519cbc62ffdbd22b000fe"), "user_id" : 81, "stuff" : 12 }
可以通过调用MongoDB javascript驱动程序的updateOne()方法来更改user_id字段。
这是示例代码:
db.collection('examples2').find(query).toArray(function(err, docs) {
if (err) throw (err)
docs.forEach(function (doc) {
if (doc.user_id === 81) {
dcnt++
im_array.push(doc._id)
console.dir(doc)
}
if (doc.user_id === "") { //empty?
dcnt++
im_array.push(doc._id)
console.dir(doc)
}
})
})
setTimeout(function() {
console.log("\nPrinting list of objectids\n")
for (var i = 0; i < im_array.length; i++) {
console.log(im_array[i])
}
console.log("\nUpdating Documents...\n")
for (var j = 0; j < im_array.length; j++) {
idObj = new ObjectID(im_array[j])
db.collection('examples2').updateOne( { "_id" : idObj }, { "$set" : { "user_id" : j + 27 } }, function(err2, doc2) {
if (err2) throw err2
})
}
}, 5000)
setTimeout(function() {
db.collection('examples2').find( { "user_id" : 10 })
console.log('\nTotal number of documents processed ' + dcnt + '\n')
db.close()
}, 12000)
由于处理是异步的,所以我有点粗糙,并且使用setTimeout(),其中使用基于promise的处理可能更好。
无论如何,以上代码将更新包含等于81的user_id字段的文档:
{ "_id" : ObjectId("56c519bac62ffdbd22b000fd"), "user_id" : 27, "stuff" : 11 }
{ "_id" : ObjectId("56c519cbc62ffdbd22b000fe"), "user_id" : 28, "stuff" : 12 }
也考虑在user_id字段上创建唯一索引。 这样,任何尝试创建或更新文档而不包含正确格式的user_id的代码都将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.