繁体   English   中英

MongoDB:使用聚合/投影获取嵌套在数组中的对象的所有内容

[英]MongoDB : Getting all the content of an object nested in an array using aggregation/projection

我在使用投影/聚合返回嵌套数组myShows.showChoices内部的对象时遇到问题。 (如果那是解决此问题的正确方法)。

每当我尝试通过查找节目的名称或ID来尝试使用.find()时,它都只会返回名称或ID,而不包含任何其他内容。 我试图返回对象的所有内容。 包括名称,概述,poster_path等...(本质上是对象本身)

我的架构:

const userSchema = new Schema({
email:{
    type: String,
    unique: true,
    lowercase: true,
    trim: true,
    required: 'Please Provide an email address'
},
name: {
    type: String,
    required: 'Please supply a name',
    trim: true,
},
myShows: {
    topRated: [],
    showChoices: []
});

我将$推入myShows.showChoices的对象看起来像

{
 name: "Name of Show",
 poster_path:"/x2WKIbiwhLoWgLFbT2I0Gwq8U1J.jpg",
 genre_ids: [37, 878],
 overview: "show description",
 id: 63247
}

我努力了:

const show = await User.find(
    { _id: req.user.id },
    { showChoices: { $elemMatch: { name: "Name of Show" } }   }
)

更新:1

以及投影/聚合的几种变体。 这是我的最新尝试。 (坚持上一次$ match之后的操作。)

const show = await User.aggregate([
            { "$match": {
              "_id" :  req.user._id,
              "myShows.showChoices.id": showIDVar
            }},
            { $unwind: "$myShows.showChoices" },
            { $match: {
                "myShows.showChoices.id": showIDVar
            }},
        ])

我认为我过去的.find()查询的问题是我只在搜索节目的名称或ID(而不是_id)

const show = await User.find(
        { _id: req.user.id },
        { "myShows.showChoices": { name: "Name of Show" }   }
    )

这只会返回节目本身的名称。 无论如何,仅通过查询名称就能返回对象的所有内容吗?

有关如何处理此问题的任何建议?

        // Expected output is to have 
const show =
        {
         name: "Name of Show",
         poster_path:"/x2WKIbiwhLoWgLFbT2I0Gwq8U1J.jpg",
         genre_ids: [37, 878],
         overview: "show description",
         id: 63247
        };

你快到了; 只需要添加$project阶段:

const show = await User.aggregate([
            { "$match": {
              "_id" :  req.user._id,
              "myShows.showChoices.id": showIDVar
            }},
            { $unwind: "$myShows.showChoices" },
            { $match: {
                "myShows.showChoices.id": showIDVar
            }},
            { $project: {
                "myShows.showChoices.name": 1,
                "myShows.showChoices.poster_path": 1,
                "myShows.showChoices.genre_ids": 1,
                "myShows.showChoices.overview":1


            }},
        ])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM