Reputation: 47921
I would like to return the count of an embedded collection in a query in mongodb.
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]
});
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.
Upvotes: 1
Views: 4874
Reputation: 42362
See Mongo docs discussion of $size operator here.
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.
Upvotes: 5