MongoDB 检查键值是否存在,只更新部分字段
MongoDB check if key value exists and update only some fields
假设我有一个 MongoDB 集合“people”,其形式为
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "rowing",
fixed: 1
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
}
]
以及要插入表格的新数据
var data = [
{
name: "Paul", // name exists, so keep "fixed" at 1
hobby: "archery",
fixed: 4
},
{
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
我想insert/update收集新数据。但是,如果已经存在具有相同“名称”的文档,我不想更新“固定”。插入以上数据后的结果应该是
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "archery", // updated
fixed: 1 // not updated, because name existed
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
},
{ // newly inserted document
_id: [OBJECT_ID_4],
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
数据包含大量文档,所以如果可能的话,我想在一次查询中实现。实现这一目标的最佳方法是什么?非常感谢!
bulkWrite with updateOne's with $upsert:true 似乎最适合你...
bulkWrite 不执行查找操作。
它(在我的例子中)对于控制它是否会创建另一个文档是必要的。
就我而言,我只是在 insert/create 方法之前使用查找检查。
if (collection.find({"descr":descr}).limit(1).length === 1) {
//...create method
console.log('Exists')
}
假设我有一个 MongoDB 集合“people”,其形式为
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "rowing",
fixed: 1
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
}
]
以及要插入表格的新数据
var data = [
{
name: "Paul", // name exists, so keep "fixed" at 1
hobby: "archery",
fixed: 4
},
{
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
我想insert/update收集新数据。但是,如果已经存在具有相同“名称”的文档,我不想更新“固定”。插入以上数据后的结果应该是
[
{
_id: [OBJECT_ID_1],
name: "Paul",
hobby: "archery", // updated
fixed: 1 // not updated, because name existed
},
{
_id: [OBJECT_ID_2],
name: "Selena",
hobby: "drawing",
fixed: 2
},
{
_id: [OBJECT_ID_3],
name: "Emily",
hobby: "jogging",
fixed: 3
},
{ // newly inserted document
_id: [OBJECT_ID_4],
name: "Peter",
hobby: "knitting",
fixed: 5
}
]
数据包含大量文档,所以如果可能的话,我想在一次查询中实现。实现这一目标的最佳方法是什么?非常感谢!
bulkWrite with updateOne's with $upsert:true 似乎最适合你...
bulkWrite 不执行查找操作。 它(在我的例子中)对于控制它是否会创建另一个文档是必要的。 就我而言,我只是在 insert/create 方法之前使用查找检查。
if (collection.find({"descr":descr}).limit(1).length === 1) {
//...create method
console.log('Exists')
}