Mongo,使用数组查询集合

编程入门 行业动态 更新时间:2024-10-10 09:20:16
本文介绍了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,使用数组查询集合

本文发布于:2023-11-25 21:11:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631363.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   Mongo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!