MongoDb 通过过滤/排序查询嵌入式集合
让我们想象一个常见的博客引擎(仅作为示例)。该模型将由帖子集合和嵌入的评论“集合”组成。
现在,我只需要获取最近 10 条评论以及我的帖子数据。
- 这样做的最佳方法是什么?
- 这是一个有价值的优化吗? (除了减少网络流量之外)
PS 我使用官方 C# 驱动程序 + Fluent-mongo,但我可以出于一个好的原因放弃 linq。
Let's imagine a usual blog engine (just for example). The model would consist of Posts collection with embedded Comments "collection".
Now, I need to get only 10 recent comments along with my Post data.
- What's the best way of doing this?
- Is this a valuable optimization? (apart from reducing network traffic)
P.S. I use official C# driver + fluent-mongo but I can give up linq for a good cause.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用 Slice 命令来检索数组的子集(最后 10 个)吗?
比如:
当我不得不做类似的事情时,我在官方文档中发现了这一点。
链接: http://www.mongodb.org /display/DOCS/Retriving+a+Subset+of+Fields#RetrivingaSubsetofFields-RetrivingaSubrangeofArrayElements
我发现在 C# 中使用 slice 命令的最简单方法是:
Couldn't you use the Slice command for retrieving a subset of the array (the last 10)?
Something like:
I found this on the official documentation when I had to do something similar.
Link: http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements
The easiest way I could find to use the slice command with C# is:
为什么不使用最新评论的专门集合呢?发布评论时,您必须执行两次插入,但获取最新评论很简单。通常,您获取这些内容的频率比发布新评论的频率要高得多。
正如 Steve B 指出的,这通常是一个“视图”,因为该集合可能包含与帖子集合中的评论略有不同的信息。例如,您可能希望在每个评论中存储帖子 ID 和帖子名称,以便可以显示相应的链接。
您可以使用 上限集合,例如 100 个元素,它会自动删除旧评论(即实现 FIFO)
Why not use a dedicated collection of most recent comments? You'll have to perform two inserts when a comment is posted, but fetching the most recent comments is simple. Typically, you would fetch these much more often than a new comment is posted anyway.
As Steve B pointed out, this is typically a 'view' in the sense that this collection might contain slightly different information than the comments within the post collection. For example, you might want to store the post id and post name in each comment so you can display a corresponding link.
You could use a capped collection of, say 100 elements, which automatically drops old comments (i.e., implements a FIFO)