Returning custom fields in MongoDB

梦想的初衷 提交于 2020-01-06 19:54:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/8639646/returning-custom-fields-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!