在更新查询中使用 $not 或 $ne
Use $not or $ne in update query
我应该在查询中使用 $not
还是 $ne
:
Mytable.update({ TheThing: Thing,
'UpdatedInfo.NewInfo': {$ne: ThisNewestInfo} }, {
$push: {
UpdatedInfo: {
TheDate: ThisDate,
NewInfo: ThisNewestInfo,
Past: OriginalInfo
}
}
},
function (err, result) {
if (err){
throw new Error(err.message);
}
}
如果我 only
想在 ThisNewestInfo
已经存在于 UpdatedInfo
数组中时更新文档,在 NewInfo
对象元素。试图了解 $not
和 $ne
之间的区别。
还有:
如果文件开头不包含UpdatedInfo
字段呢?我应该如何更改上面的更新查询?这意味着如果 UpdatedInfo
不存在,它会添加 UpdatedInfo
,稍后,比如第二天,再次更新文档时检查 ThisNewestInfo
是否不存在。
这实际上取决于您的 collection。
在这种情况下,$ne 和 $not 之间的主要区别在于,$not 执行 逻辑析取 。也就是说,如果您的文档没有 UpdatedInfo
字段,则使用 $not 会推送文档,而使用 $ne 则该文档不会发生任何事情。
因此,如果您所有 collection 的文档都有 UpdatedInfo
字段,最好使用 $ne.
编辑
根据您的编辑,您提到的 UpdatedInfo 可能不会出现在文档中。在这种情况下,您应该使用 $not。 $ne 将无法更新没有 UpdatedInfo 字段的文档。
请记住:$not 检查是否存在键和值,而 $ne 仅检查值并忽略在查询中没有特定键的文档。
我应该在查询中使用 $not
还是 $ne
:
Mytable.update({ TheThing: Thing,
'UpdatedInfo.NewInfo': {$ne: ThisNewestInfo} }, {
$push: {
UpdatedInfo: {
TheDate: ThisDate,
NewInfo: ThisNewestInfo,
Past: OriginalInfo
}
}
},
function (err, result) {
if (err){
throw new Error(err.message);
}
}
如果我 only
想在 ThisNewestInfo
已经存在于 UpdatedInfo
数组中时更新文档,在 NewInfo
对象元素。试图了解 $not
和 $ne
之间的区别。
还有:
如果文件开头不包含UpdatedInfo
字段呢?我应该如何更改上面的更新查询?这意味着如果 UpdatedInfo
不存在,它会添加 UpdatedInfo
,稍后,比如第二天,再次更新文档时检查 ThisNewestInfo
是否不存在。
这实际上取决于您的 collection。
在这种情况下,$ne 和 $not 之间的主要区别在于,$not 执行 逻辑析取 。也就是说,如果您的文档没有 UpdatedInfo
字段,则使用 $not 会推送文档,而使用 $ne 则该文档不会发生任何事情。
因此,如果您所有 collection 的文档都有 UpdatedInfo
字段,最好使用 $ne.
编辑
根据您的编辑,您提到的 UpdatedInfo 可能不会出现在文档中。在这种情况下,您应该使用 $not。 $ne 将无法更新没有 UpdatedInfo 字段的文档。
请记住:$not 检查是否存在键和值,而 $ne 仅检查值并忽略在查询中没有特定键的文档。