查询返回 mongodb 嵌入式集合中的项目数 [英] query returning count of items in mongodb embedded collection

查看:51
本文介绍了查询返回 mongodb 嵌入式集合中的项目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 mongodb 的查询中返回嵌入集合的计数.

I would like to return the count of an embedded collection in a query in mongodb.

假设我有一个名为 profile 的集合

Say I have a collection called profiles

var ProfileSchema = new Schema({
  uname: {
    type: String,
    required: true,
    index: true,
    unique: true
  },
  fname: String,
  lname: String,
  posts: [ObjectId]
}); 

如何查询以便选择 uname、frame、lame、posts.length?我不想通过网络返回帖子集合,因为用户可以拥有数百个帖子.我是否应该将帖子 ID 嵌入到个人资料架构中?也许我应该摆脱它,因为已经为帖子定义了另一个集合,所以我基本上使用 Profile.posts 作为外键的嵌入式集合.

How can I query it so that I select uname, frame, lame, posts.length ? I don't want to return the posts collection over the wire since users can have hundreds of posts. Should I even embed the post ids in the profile schema? Maybe I should just get rid of it since there is already another collection defined for posts, so I'm essentially using Profile.posts as an embedded collection of foreign keys.

推荐答案

参见 Mongo 文档讨论 $size 运算符 这里.

See Mongo docs discussion of $size operator here.

简而言之,您可以使用 $size 运算符根据确切的数组大小进行查询,但您无法取回数组大小,也无法根据数组大小范围进行查询.

In a nutshell, you can query based on exact array size with $size operator, but you can't get back array size, nor can you query based on array size range.

建议对您有用的内容-保留另一个字段,即帖子计数-可以在查询中用作过滤器/范围,并且可以在需要知道数组有多大时返回它.无论帖子是存储在其他地方还是嵌入到数组中,如果您根据帖子数量进行查询或过滤,此字段将非常有用.

What the suggests would work well for you - keep another field which is the count of posts - that may be used both in queries as a filter/range and you can return it when you need to know how big an array is. Whether the posts are stored elsewhere or embedded in the array, this field would be very useful if you do querying or filtering based on number of posts.

有一个非常类似的问题,有类似的建议.

There is a very similar question with similar suggestions.

这篇关于查询返回 mongodb 嵌入式集合中的项目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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