Mongodb:查询文档中的数组元素 [英] Mongodb: Querying array elements within a document
问题描述
我有一个要查询的收藏集,如下所示:
I have a collection I'd like to query as follows:
- 返回所有文档
- 最多2条评论(例如,一片,0条,1条或2条评论)
- 所有评论的观看次数必须大于10
似乎我需要创建一个函数来分别评估每个文档,但是目前尚不清楚该如何完成,特别是考虑到我要进行切片并返回最多n个符合该条件的项目.
It seems like I need to create a function to evaluate each document individually, but it's not clear how that's done, particularly given I want to do a slice and return up to n items matching that criteria.
示例架构:
{
title: "One",
comments: [
{
title: "comment1",
views: 9
},
{
title: "comment2",
views: 10
},
{
title: "comment3",
views: 11
},
{
title: "comment4",
views: 12
},
]
}
我想做类似的事情:
db.collection.find({"comments.views": {$gt: 10}}, {comments:{$slice: 2}})
但是,这将返回任何带有> 10个视图的注释的文档,然后切片2个注释...我想返回那些包含> 10个项目的注释.我不能在客户端上执行此操作,而使用$ slice而不丢失一些注释,因此我需要在数据库上执行此操作.有想法吗?
But this returns any document with a comment with > 10 views, and then slices 2 comments... I want to return on those comments which have > 10 items. I cannot do it on the client AND use $slice without losing some comments, so I need to do it on the DB. Thoughts?
推荐答案
但是这将返回带有注释的任何文档,这些文档具有> 10个视图,然后 切片2条评论
But this returns any document with a comment with > 10 views, and then slices 2 comments
这是过滤多级嵌入式文档的行为,通常匹配的过滤器将返回整个文档,而不是子集.
This is the behavior of filtering multi level embedded document, normally the matching filter would return the whole document, not the subsets.
通常使用位置运算符$来匹配更新中的子文档.但是该功能尚未在返回说明符中实现.
Usually positional operator $ used to match the sub documents in updates. But the feature is not yet implemented in return specifiers.
mongo中已经存在一个未解决的问题,该支持在字段中返回位置($)运算符以返回指定值 r. (如果您确实需要此功能,请登录以投票)
There is an outstanding issue already in mongo Support for positional ($) operator in fields to return specifier. (Please login to vote if you really needed the feature)
所以您必须处理
- 最多2条评论(例如,一片,0条,1条或2条评论)
通过所有集合循环遍历您的应用程序.
part in your application by loop through all collections.
这篇关于Mongodb:查询文档中的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!