不确定这是否可能,但是,
我的集合中只有很少的文档
。 文档
中有重复项,唯一的区别是时间戳
例如:
{
name: 'abc',
verified: false,
createdAt: 'timestamp1'
},
{
name: 'abc',
verified: false,
createdAt: 'timestamp2'
},
{
name: 'abc',
verified: false,
createdAt: 'timestamp3'
},
{
name: 'eee',
verified: false,
createdAt: 'timestamp1'
},
{
name: 'eee',
verified: false,
createdAt: 'timestamp2'
}
可以看到,name
字段有重复项,但我只想更新最新的 timestamp
,verified
到 真
但是 timestamp
确实是随机捕捉的。
我可以使用 update 和 $in
但这将更新所有文档,而不仅仅是具有最新 timestamp
的文档
Mongoose 创建的时间戳示例
},
"updatedAt": {
"$date": "2018-06-08T23:39:49.310Z"
},
"createdAt": {
"$date": "2018-06-08T23:21:15.669Z"
},
这是我使用 $in
的简单代码
const names = ['abc', 'eee'];
Model.update({
'name': {
$in: names
}
}, { verified: true }, { multi: true });
在此先感谢您的帮助。
最佳答案
通过 createdAt
查找指定名称的最新文档:
const names = ['abc', 'eee'];
collection.aggregate(
[
{$match: {'name': {$in: names}}},
{$group: {_id: '$name', createdAt: {$max: '$createdAt'}}},
]);
将查询结果保存在变量 result
中作为 Array
或 cursor
。
然后你可以更新文档:
results.forEach((newestDocumentForName) => collection.update({_id: newestDocumentForName['_id']}, {/*your set operation*/});
关于javascript - Mongoose 使用 $in 并且只用最近的时间戳更新一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50777521/