如何解决如何从mongodb中的对象数组获取公共属性
下面是示例文档
[
{
"name": "john"
"attribute":[
{
nameAttr: "abc"
tagAttr: "zxs"
},{
nameAttr: "asd"
tagAttr: "zxs"
},{
nameAttr: "lll"
tagAttr: "zxs"
},]
},{
"name": "john"
"attribute":[
{
nameAttr: "abc"
tagAttr: "zxs"
},{
nameAttr: "sss"
tagAttr: "zxs"
},]
我想将所有通用nameAttr输出都输出为[“ abc”,“ asd”],因为它们在两个文档中都是通用的 我仅能将nameAttr与项目一起投影,但不知道如何进一步进行 db.collection.aggregate([
{
$project: {
"attribute.nameAttr": 1,}
}
])
解决方法
您可以使用Apple's opensource documentation for the Human Interface system将所有属性名称收集到一个数组数组中,然后将$group与$reduce结合使用以获得常用的名称:
db.collection.aggregate([
{
$group: {
_id: null,attributes: { $push: "$attribute.nameAttr" }
}
},{
$project: {
commonAttributes: {
$reduce: {
input: "$attributes",initialValue: { $arrayElemAt: [ "$attributes",0 ] },in: { $setIntersection: [ "$$value","$$this" ] }
}
}
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。