- Node :0.10.13
- 蒙戈:2.4.1
- mongodb-native :1.3.23
问题:
如何通过一次调用插入简单字符串数组作为新文档?我之前不想转换它。我在这里寻找一些蒙戈魔法。 $push
、$each
似乎不适用于插入。
var newTags = [];
newTags.push("tagA");
newTags.push("tagB");
// with this lodash conversion the batch insertion works fine.
// ["tagA", "tagB"] -> [{name: "tagA", name: "tagB"}]
// newTags = _.map(newTags, function(key) {return {'name': key}});
db.collection('tags').insert(newTags, {w: 1}, function (err, result) {
});
我对“不工作”的定义
Mongo 确实插入了 newTags,但从每个字符串创建一个文档,如下所示。
我明白为什么这样做
{
"_id": "111111116c021a165abcdd16",
"0": "t",
"1": "a",
"2": "g",
"3": "A"
},
{
"_id": "111111126c021a165abcdd17",
"0": "t",
"1": "a",
"2": "g",
"3": "B"
}
但应该是
{
"_id": "111111116c021a165abcdd16",
"name": "tagA"
},
{
"_id": "111111126c021a165abcdd17",
"name": "tagB"
}
最佳答案
据我所知,这是不可能的,因为对于插入,MongoDB 要么接受单个文档对象,要么接受此类对象的数组,但不接受标量数组。
这在 IMO 中是有道理的,因为 MongoDB 如何知道您想要将这些标量映射到特定字段(在本例中为 name
)?这是应用程序逻辑,而不是数据库逻辑。
关于javascript - Node mongodb-native : insert an array of strings as documents,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20801893/