MongoDB的查询,结果只有特定的元素融入到对象的数组 [英] Mongodb query, result only specific elements into array of objects

查看:171
本文介绍了MongoDB的查询,结果只有特定的元素融入到对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,导致我在MongoDB中查询。

I have one problem to result my query in mongodb.

我有这样的文件,一个集合: https://github.com /pedrualves/document/blob/master/school.js

I have one collection of documents like this: https://github.com/pedrualves/document/blob/master/school.js

我可以用搜索这个文件没有问题
页:32

I can search this document without problems using "pages": 32

不过,我不能显示的结果是这样的:

But, I can't show the results like this:

{
"book": [
 {
  "pages": 32,
  "title": "a"
 },
 {
  "pages": 32,
  "title": "c"
 },
 {
  "pages": 32,
  "title": "d"
 }
]
}

有人,能帮助我解决这个问题?

Someone, could help me with this problem?

感谢您

推荐答案

您可以使用下面的聚合管道得到期望的结果,而不是因为在 16Mb的额度 与聚集过程中的 $开卷 作为大集合:

You could use the following aggregation pipeline to get the desired result, not the best solution because of the 16Mb limit with aggregation during $unwind for large collections:

db.school.aggregate([
    {
        "$match": { "students.class.book.pages": 32 }
    },
    { "$unwind": "$students" },
    { "$unwind": "$students.class.book" },
    {
        "$match": { "students.class.book.pages": 32 }
    },
    {
        "$group": {
            "_id": null,
            "book": {
                "$push": {
                    "pages": "$students.class.book.pages",
                    "title": "$students.class.book.title"
                }
            }
        }
    }
])

这篇关于MongoDB的查询,结果只有特定的元素融入到对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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