简体   繁体   中英

Collection.find() for array inside object

I have a Meteor app that has a collection of chat groups. Each document in this collection looks like this:

{groupname: 'name', whitelist: ['person1', 'person2', 'person3'], messages:['message1', 'message2', 'message3']}

To show each person with an account what groups they are part of, I need a page with a list of those groups they're allowed in. How can I use a find() command to return all of the documents whose whitelist array contains the user's name?

Something like this:

ChatGroups.find({whitelist: Meteor.user().username});

This assumes that username is the property you want to match against. You don't need to do anything special to search within an array in this case - mongo will do the correct thing (compare username to each element of each whitelist and return those documents that match).

To search in MongoDB by array items - use $in operator:

ChatGroups.find({
   whitelist: {
      $in: [Meteor.user()._id]
   }
});

Reference: Comparison Query Operators > $in

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