Linked Questions

Popular Questions

How can can I query mongodb to compare arrays of objects?

Asked by At

I am designing a messaging feature. I have a users collection which contains things like ID, first name, and last name. I also have a messages collection which contains an array of values like author ID, message body etc. And finally I have a conversations collection which has an ID and participants, which is an array of user IDs.

I am thinking this may not be a good structure since I want to be able to run a query that returns all the users (ID, first name and last name) that a given user has message history with. The way it is, I can't seem to run a query that will return all the information that I need. Do I need to restructure, or is there a way to run this query?

Here is an example of the structure:

Conversation:
{ id: 123
  participants: ['<user ID here>', '<user ID here>'],
}

User:{
id:654,
firstName: John
lastName: Doe

Message:
{ sender: 'john', 
  content: 'howdy', 
  time_created: new Date(),
  converstationId: 123
},
{ sender: 'marry', 
  content: 'good u', 
  time_created: new Date(),
  converstationId: 123 
},

I tried a few variations of the following, but I never got anything but an empty array back:

db.Users.aggregate([
    {
       $unwind: "$participants"
    },
    {
       $lookup:
          {
             from: "conversations",
             localField: "participants",
             foreignField: "_id",
             as: "response"
         }
    },
    {
       $match: { "response": { $ne: [] } }
    }
 ])

So my question is: How can I get all the users that correlate to user IDs in the participants array?

Related Questions