[英]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.