MongoDB汇总以有条件地更新所有集合中的用户名,并使用大量文档
我们有一个UserLogin
收集,并在Mongo Atlas中拥有大量文档。我要编写一个聚合以降低用户名
字段,如果该字段不在小写中。该藏品有大量文件(500,000北部)。
我编写了以下汇总函数,如果字段具有不小写的任何字符,它会在字段中进行小写。我正在使用$ MATCH
查询如果用户名字段中的值及其小写值不等,在这种情况下,使用$ set
我是用小写它的价值。
await userLogin.aggregate([
{
'$match': {
'$expr': {
'$ne': [
'$username', {
'$toLower': '$username'
}
]
}
}
}, {
'$set': {
'username': {
'$toLower': '$username'
}
}
}
,
{
$out: 'userLogin',
},
]);
它适用于具有大写字符的用户名的文档。但是,如果用户名已经处于小写状态,则将删除文档。我在做什么错?
编辑:由于用户名在其上具有唯一的索引,如果集合中已经存在具有小写的用户名的文档,则应跳过当前正在处理的文档(用户名获得的文档)。
We have a userLogin
collection with large number of documents in Mongo Atlas. I’ve to write an aggregation to lowercase the username
field if the field is not in lowercase. The collection has large number of documents (north of 500,000).
I've written the following aggregate function, which does lowercase the field, if the field has any character that is not in lowercase. I'm checking with $match
if the value in username field and its lowercase value are not equal, in that case, using $set
I'm setting the field with lowercase value of it.
await userLogin.aggregate([
{
'$match': {
'$expr': {
'$ne': [
'$username', {
'$toLower': '$username'
}
]
}
}
}, {
'$set': {
'username': {
'$toLower': '$username'
}
}
}
,
{
$out: 'userLogin',
},
]);
It works fine for documents with usernames that have uppercase characters in it. However, if the username is already in lowercase, document gets deleted. What am I doing wrong?
Edit: Since username has a unique index on it, in case when a document with lowercase username already exist in the collection, document currently under processing (username getting lowercased) should be skipped.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的情况下,
$ match
条件正在筛选出已在persons
中的文档,这是不必要的。简而言之应该足够:这将设置
用户名
,无论其是否具有大写字符。另外,
$ out
,完全替换了集合,这就是为什么使用$ MATD
运行文档的原因。删除$ MATD
,或使用$ MERGE
阶段而不是$ of
。这是指向
$ MERGE
documentation < /a>。应该是这样的:
The
$match
condition in your case, is filtering out the documents, which are already inlowercase
, it's unnecessary. Simply this should suffice:This will set the
username
, regardless of whether it has uppercase characters or not.Also
$out
, replaces the collection completely, that's why the documents seem to be deleted, when ran with$match
. Either remove$match
, or use$merge
stage instead of$out
.Here's the link to
$merge
documentation.It should be something like this: