Mongo,用数组查询集合

时间:2014-06-21 14:07:21

标签: mongodb mongoose

我有这个名为组织的集体:

[
  {
    "_id": "53a58a02f1001e7fd28f5aec",
    "orgId": 5,
    "title": "Org A",
    "members": [
      {
        "tier": 1,
        "user": "53a58a02f1001e7fd28f5ae8"
      },
      {
        "tier": 2,
        "user": "53a58a02f1001e7fd28f5ae9"
      },
      {
        "tier": 3,
        "user": "53a58a02f1001e7fd28f5aea"
      }
    ]
  },
  {
    "_id": "53a58a02f1001e7fd28f5aed",
    "orgId": 6,
    "title": "Org B",
    "members": [
      {
        "tier": 1,
        "user": "53a58a02f1001e7fd28f5ae9"
      },
      {
        "tier": 3,
        "user": "53a58a02f1001e7fd28f5aea"
      }
    ]
  }
]

我想运行一个查询,该查询返回给定用户所属的所有组织。

我试过了:

mongoose.model('organization').find({}, function(err, organizations){
    var usersOrganization = [];

    for(var i=0;i<organizations.length;i++){
      for(var f = 0;f<organizations[i].members.length;f++){
        if(String(organizations[i].members[f].user) === user){
          usersOrganization.push(organizations[i]);
        }
      }
    }

    callback.send(200, usersOrganization);
  })

首先让所有组织循环遍历它们和所有成员。将成员与给定用户匹配并将其推入阵列。

它有效,但我想知道是否有任何智能查询可以做得更漂亮?

1 个答案:

答案 0 :(得分:1)

您可以使用点符号匹配数组中的字段,因此您可以将查询简化为:

mongoose.model('organization')
    .find({'members.user': user}, function(err, usersOrganizations){
        callback.send(200, usersOrganization);
    }
);