这是我的文档格式
[
{
"name" : "test1",
"other_name" : "TEST1_1",
"values" : ["11", "12", "13", "14"]
},
{
"name" : "test2",
"other_name" : "TEST2_1",
"values" : ["21", "22", "23", "24"]
},
{
"name" : "test3",
"other_name" : "TEST3_1",
"values" : ["11", "32", "13", "14"]
}
]
我希望输出为:
["11", "12", "13", "14", "21", "22", "23", "24", "32"]
我应该也可以对它们进行过滤(仅对values数组进行过滤),orderby(仅对values数组进行ordering)。
您能帮我吗?
我尝试过:
db.collection.distinct('values', { "values" : /32/ }).sort();
但这会返回所有"11", "32", "13", "14"
之类的值,我只需要特定的值,您能帮上忙吗?
答案 0 :(得分:0)
您需要使用MongoDB aggregation operations来获得所需的输出。
我们用DBI::dbGetQuery(con0, "
select id_no, replace(website_link,'msn','toast') as website_link
from personal_websessions
where website_link regexp '\\bmsn\\b'
union
select id_no, website_link
from personal_websessions
where not website_link regexp '\\bmsn\\b' ")
# id_no website_link
# 1 1 google.com
# 2 2 stackoverflow.com
# 3 3 toast.com
# 4 4 msnnews.com
运算符将values
展平。我们对值进行排序。然后,我们将所有文档$unwind
$group
并存储所有值(重复)。使用$reduce
,我们将生成具有唯一值的新数组。
注意:聚合返回对象数组
db.collection.aggregate([
{
$unwind: "$values"
},
{
$sort: {
values: 1
}
},
{
$group: {
_id: null,
values: {
$push: "$values"
}
}
},
{
$project: {
_id: 0,
values: {
$reduce: {
input: "$values",
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$cond: [
{
$in: [
"$$this",
"$$value"
]
},
[],
[
"$$this"
]
]
}
]
}
}
}
}
}
])
不清楚仅特定值
是什么意思