如何让员工获得mongodb过去和现在的工作?

时间:2017-12-08 14:15:45

标签: mongodb

我是NoSQL数据库的新手,因此我正在努力解决结构和查询问题。

我目前正在使用mongodb中的公司数据集,该数据集具有以下结构:

{
    "_id": "52cdef7c4bab8bd675297d8b",
    "name": "AdventNet",
    "permalink": "abc3",
    "category_code": "enterprise",
    "number_of_employees": 600,
    "founded_year": 1996,
    "relationships": [{
        "is_past": true,
        "title": "CEO and Co-Founder",
        "person": {
            "first_name": "Sridhar",
            "last_name": "Vembu",
            "permalink": "sridhar-vembu"
        }
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "person": {
            "first_name": "Neil",
            "last_name": "Butani",
            "permalink": "neil-butani"
        }
    }, {
        "is_past": true,
        "title": "Western Regional OEM Sales Manager",
        "person": {
            "first_name": "Ian",
            "last_name": "Wenig",
            "permalink": "ian-wenig"
       }
    },
    ...
    }]
}

我想要实现的是获得一个包含每个员工姓名及其过去和现在所有工作的新集合,例如:

{
    "_id": "neil-butani",
    "first_name": "Neil",
    "last_name": "butani",
    "employments": [{
        "is_past": false,
        "title": "CEO and Co-Founder",
        "company_name": "AdventNet"
    }, {
        "is_past": true,
        "title": "VP of Business Dev",
        "company_name": "Example Inc.""
    }]
}

在SQL中,我会编写使用companies表连接employees表的查询,但是我可以或应该使用哪些运算符和概念来获取mongodb中的所需结果?

1 个答案:

答案 0 :(得分:1)

您可以$unwind$group permalink收集所有employments后跟$out来写入新收藏。

这样的东西
db.collection_name.aggregate([
  {
    "$unwind": "$relationships"
  },
  {
    "$group": {
      "_id": "$relationships.person.permalink",
      "first_name": {
        "$first": "$relationships.person.first_name"
      },
      "last_name": {
        "$first": "$relationships.person.last_name"
      },
      "employments": {
        "$push": {
          "is_past": "$relationships.is_past",
          "title": "$relationships.title",
          "company_name": "$name"
        }
      }
    }
  },
  {
    "$out": "new collection name"
  }
])