返回 MongoDB 中的自定义字段
我有一个 mongoDB 集合,其中包含一个数组字段,表示用户所属的列表。
user {
screen_name: string
listed_in: ['list1', 'list2', 'list3', ...] //Could be more than 10000 elements (I'm aware of the BSON 16MB limits)
}
我使用 *listed_in* 字段来获取成员列表
db.user.find({'listed_in': 'list2'});
我还需要查询特定用户并知道他是否是某些列表的成员
var user1 = db.findOne({'screen_name': 'user1'});
在这种情况下,我将获得 *listed_in* 字段及其所有成员。
我的问题是: 有没有办法在 mongoDB 中预先计算自定义字段? 我需要能够获取这样的字段,user1.isInList1,user1.isInList2
现在我必须在客户端通过迭代 *listed_in 来完成此操作* 用于了解用户是否是“list1”成员的数组,但 *listed_in* 可能有数千个元素。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
并不真地。 MongoDB 没有任何“计算列”的概念。所以您要查找的查询不存在。
在您的情况下,您基本上是在尝试推送客户端-side
for
循环到服务器上。然而,某些进程仍然需要执行for
循环。坦率地说,对于客户端或服务器来说,循环 10k 个项目实际上并不是那么多工作。这里唯一真正的节省是防止网络上出现额外的数据。
如果您确实想节省网络流量,则需要重组数据模型。这种重组可能涉及两个查询来读取和写入,但传输的数据较少。但这就是权衡。
Not really. MongoDB does not have any notion of "computed columns". So the query you're looking for doesn't exist.
In your case you're basically trying to push a client-side
for
loop onto the server. However, some process still has to do thefor
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.