简体   繁体   English

如何在mongodb中查询对象数组

[英]How do I query in an array of objects in mongodb

I have a db object looking like this: 我有一个数据库对象看起来像这样:

{
   user_name: 'string',
   skills: [ 
       { skill: 'skill1', lvl: 3 } 
   ],
   wantsToLearn: [ 
       {skill: 'skill2' } 
   ]
}

I want to make a query wherein I find all users with a wantToLearn skill matching with one pf my input user's skill (regardless of lvl) AND vice versa. 我想进行查询,以查找所有具有wantToLearn技能并与我输入的用户技能(无论lvl如何)相匹配的用户,反之亦然。 Basically, I want to be able to find all users with a match between a skill and something they want to learn. 基本上,我希望能够找到一个技能与他们想要学习的东西相匹配的所有用户。

I have looked at the mongodb documentation and am still a bit clueless on how to do this the best way. 我看过mongodb文档,但对如何最好地做到这一点仍然一无所知。 I am new to databases in general except for some sql. 除了一些sql之外,我一般都不熟悉数据库。

Any pointers would be very appreciated! 任何指针将不胜感激!

If you want to find all users matching your given skill, all you have to do is : 如果要查找与您的给定技能匹配的所有用户,您要做的就是:

db.getCollection('yourCollection').find({"wantsToLearn.skill": "skill2" })

That's the way you query subdocuments in MongoDB, even in arrays 这就是您在MongoDB中甚至在数组中查询子文档的方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM