返回 MongoDB 中的自定义字段

发布于 2024-12-22 20:27:49 字数 661 浏览 2 评论 0原文

我有一个 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.isInList1user1.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

弃爱 2024-12-29 20:27:49

我的问题是:有没有办法在 mongoDB 中预先计算自定义字段?

并不真地。 MongoDB 没有任何“计算列”的概念。所以您要查找的查询不存在。

现在我必须在客户端通过迭代 *listed_in* 数组来了解用户是否是“list1”的成员,但 *listed_in* 可能有数千个元素

在您的情况下,您基本上是在尝试推送客户端-side for 循环到服务器上。然而,某些进程仍然需要执行 for 循环。坦率地说,对于客户端或服务器来说,循环 10k 个项目实际上并不是那么多工作。

这里唯一真正的节省是防止网络上出现额外的数据。

如果您确实想节省网络流量,则需要重组数据模型。这种重组可能涉及两个查询来读取和写入,但传输的数据较少。但这就是权衡。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文