1

I have two collections - Tickets and Users. Where a user can have one to many tickets. The ticket collection is defined as follows

Ticket = {_id, ownerId, profile: {name}}

The ownerId is used to find all tickets that belong to a specific person. I need to write a query that gets me all users with no tickets.

How can i write this query without having to loop through all users, checking if the userID shows up in any Tickets?

Would a bidirectional storage cause me any performance problems ? For example, if i were to change my users collection and add an array of tickets: [ticketID, ticketID2, ...]?

Warz
  • 7,386
  • 14
  • 68
  • 120

1 Answers1

0

I'd go with the array of tickets being stored in users. As far as I know, Mongo doesn't really have a way to query one collection based on the (lack of) elements in another collection. With the array, though, you can simply do db.users.find({tickets:[]}).

Colin Valliant
  • 1,899
  • 1
  • 13
  • 20
  • I think i will take this approach. About your query though, if i am looking for 'users without any tickets', does your query read, grab all users where the field tickets exists but does not equal empty ? – Warz Jun 09 '13 at 00:01
  • Oh, you're right. I've edited the answer to find users without tickets. – Colin Valliant Jun 09 '13 at 00:28
  • Yes that does it and i modified it so that it also returns me in the case there are existing users that do not have the `tickets` field to begin with using the suggested `exists: false` idea. Thanks – Warz Jun 09 '13 at 00:40