mongodbschema-designnosql

Returning custom fields in MongoDB


I have a mongoDB collection with an array field that represents the lists the user is member of.

user { 
  screen_name: string
  listed_in: ['list1', 'list2', 'list3', ...] //Could be more than 10000 elements (I'm aware of the BSON 16MB limits)
}

I am using the *listed_in* field to get the members list

db.user.find({'listed_in': 'list2'});

I also need to query for a specific user and know if he is member of certain lists

var user1 = db.findOne({'screen_name': 'user1'});

In this case I will get the *listed_in* field with all its members.

My question is: Is there a way to pre-compute custom fields in mongoDB? I would need to be able to get fields like these, user1.isInList1, user1.isInList2

Right now I have to do it in the client side by iterating through the *listed_in* array to know if the user is member of "list1" but *listed_in* could have thousand elements.


Solution

  • My question is: Is there a way to pre-compute custom fields in mongoDB?

    Not really. MongoDB does not have any notion of "computed columns". So the query you're looking for doesn't exist.

    Right now I have to do it in the client side by iterating through the *listed_in* array to know if the user is member of "list1" but *listed_in* could have thousand elements

    In your case you're basically trying to push a client-side for loop onto the server. However, some process still has to do the for loop. And frankly, looping through 10k items is not really that much work for either client or server.

    The only real savings here is preventing extra data on the network.

    If you really want to save that network traffic, you will need to restructure your data model. This re-structure will likely involve two queries to read and write, but less data over the wire. But that's the trade-off.