在MongoDB中返回自定义字段 [英] Returning custom fields in MongoDB

查看:335
本文介绍了在MongoDB中返回自定义字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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)
}

我正在使用* listed_in *字段获取成员列表

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'});

在这种情况下,我将获得* listed_in *字段及其所有成员。

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

我的问题是:
是否可以在mongoDB中预先计算自定义字段?
我需要能够获得如下字段, user1.isInList1 user1.isInList2

现在,我必须在客户端通过遍历* listed_in *数组来知道用户是否是 list1的成员,但* listed_in *可能具有数千个元素。

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.

推荐答案


我的问题是:有没有一种方法可以预先计算mongoDB中的自定义字段?

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

不是。 MongoDB没有计算列的任何概念。因此,您要查找的查询不存在。

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


现在,我必须在客户端通过遍历* listed_in *数组可知道用户是否是 list1的成员,但* listed_in *可能具有数千个元素

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

基本上是在尝试将客户端 for 循环推送到服务器上。但是,某些过程仍必须执行 for 循环。坦率地说,遍历1万个项目对于客户端或服务器来说并没有那么大的工作。

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.

这篇关于在MongoDB中返回自定义字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆