本文介绍了Mongo,使用数组查询集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个叫做organization的大学:
I have this colleciton called organization:
[ { "_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" } ] } ]我想运行一个查询,该查询返回给定用户所属的所有组织.
I want to run a query which returns all organizations that a given user is a member of.
我尝试过:
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); })首先获取所有组织,然后遍历它们和所有成员.将成员与给定的用户匹配,并将其推入数组.
First get all organizations then loop through them and all members. Match the members with the given user and push it in to an array.
它可以工作,但是我想知道是否有任何智能查询可以使它更漂亮?
It works, but I wonder if there is any smart query to do this more pretty?
推荐答案您可以使用点符号与数组中的字段进行匹配,因此可以将查询简化为:
You can match against fields within an array using dot-notation, so you can simplify your query to:
mongoose.model('organization') .find({'members.user': user}, function(err, usersOrganizations){ callback.send(200, usersOrganization); } );更多推荐
Mongo,使用数组查询集合
发布评论