如何根据可应用于其中一个文档的条件插入新文档
我有一个集合,其中存储用户的唯一 uID,并且还必须手动注册它们。注册时,我在数组中传递多个 ID,现在我想查询注册时提供的任何 uID 是否与注册集合中的现有 uID 匹配,我想返回这些文档或只是返回一个真值,该值将告诉用户存在,以便我中止注册并为用户分配另一个 ID。
const uniqueIDs = [ "123", "156", "148"]
如果需要,我可以运行映射函数来获取这些值作为数组对象,例如
[
{
uID : "123",
},
{
uID : "156",
},
{
uID : "148",
},
]
现有集合中的示例:
{
uID : "123",
country : "abc"
},
{
uID : "486",
country : "def"
},
{
uID : "958",
country : "jkl"
},
现在我的问题是我可以从映射数组或 uiD 数组查询我的集合,以便找到现有文档吗? 如果没有找到文档,我可以通过 insertMany 之类的函数从这个唯一的 uID 插入多个文档吗?
I have a collection where I store unique uID for a user and I also have to register them manually. While registration I pass multiple IDs in an array and now I want to query if any of those uIDs provided while registration match existing uID from registered collection, I want to return those document or simply a truth value which will tell that users exist so that I abort registration and assign another id for a user.
const uniqueIDs = [ "123", "156", "148"]
If required I can run map function to get these values as object of arrays such as
[
{
uID : "123",
},
{
uID : "156",
},
{
uID : "148",
},
]
Example from existing collection:
{
uID : "123",
country : "abc"
},
{
uID : "486",
country : "def"
},
{
uID : "958",
country : "jkl"
},
Now my question is can I query my collection from mapped array or array of uiDs so that I find existing documents?
If none documents found, can I insert multiple documents from this unique uID from insertMany like function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个解决方案,尽管我想说这更像是一种黑客行为而不是常见做法。
您可以执行以下操作:
这是一个聚合管道,末尾有一个
$merge
步骤,以便将新文档插入到集合中。$facet
步骤构建您想要插入的文档并检查条件。带有$cond
的$project
使用数据覆盖它,如果条件找到现有的uID
,该数据将返回错误。这种黑客攻击有其局限性。首先,在运行之前,您的集合中至少需要有一个文档,因为它使用它作为创建新文档的基础。其次,为了使用
$merge
步骤,您需要在uID
上创建唯一索引。最后,如果列表中没有带有
uID
的文档,它将插入新文档。如果列表中存在带有uID
的文档,则会返回错误。There is a solution for this, although I would say this is more of an hack than a common practice.
You could do something like:
This is an aggregation pipeline with a
$merge
step at the end, in order to insert new documents into the collection. The$facet
steps builds the documents you want to insert and checks the condition. The$project
with the$cond
override it with a data that will return an error in case the condition founds existinguID
.There are limitation to this hack. First you need to have at least one document in your collection before running it, since it uses it as a base to create the new documents. Second, in order to use the
$merge
step you need to create a unique index on theuID
.At the end, if there are no documents with the
uID
in the list it will insert the new documents. If there are documents with theuID
in the list it will return an error.