在 mongodb 中过滤数组 [英] Filter arrays in mongodb
本文介绍了在 mongodb 中过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个集合,其中每个文档包含 2 个文档数组,如下所示.
I have a collection where each document contains 2 arrays of documents as below.
{
all_users:[
{
id:1,
name:"A"
},
{
id:2,
name:"B"
},
{
id:3,
name:"C"
}
]
selected_users:[
{
id:1,
name:"A"
},
{
id:2,
name:"B"
}
]
}
是否可以通过添加字段 selected
并根据用户名称是否存在于 selected_users
中的文档中为其分配值来合并 2 个数组代码>数组如下.
Is it possible to merge the 2 arrays by adding a field selected
and assigning a value to it based on whether the name of the user is present in a document in the selected_users
array as follows.
{
all_users:[
{
id:1,
name:"A",
selected:"yes"
},
{
id:2,
name:"B",
selected:"yes"
},
{
id:3,
name:"C",
selected:"no"
}
]
}
我想通过 id
或 name
进行检查,因为文档可能包含其他字段.我不知道如何实现这一点.
I want to check by id
or name
since the documents may contain additional fields. I can't figure out how to achieve this.
推荐答案
$map
迭代all_users
数组的循环$cond
检查条件,如果id
在选定用户id
中,则返回yes";否则否"在selected
字段$mergeObject
将当前用户对象与上面的selected
字段合并$map
to iterate loop ofall_users
array$cond
check condition ifid
is in selected usersid
then return "yes" otherwise "no" inselected
field$mergeObject
to merge current user object with aboveselected
field
db.collection.aggregate([
{
$project: {
all_users: {
$map: {
input: "$all_users",
in: {
$mergeObjects: [
"$$this",
{
selected: {
$cond: [
{ $in: ["$$this.id", "$selected_users.id"] },
"yes",
"no"
]
}
}
]
}
}
}
}
}
])
这篇关于在 mongodb 中过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文