简体   繁体   中英

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. 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. I am new to databases in general except for some 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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