【发布时间】:2019-04-03 08:30:30
【问题描述】:
假设我有以下文件:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
},
{
"_id":"5bd7a9d2604b760004947833",
"shape":"circle",
"colors": []
}
]
},
{
"_id":"5bd5ba2ca677cb000469168a",
"shapes":[
{
"_id":"5bd7a9e4604b760004947834",
"shape":"square",
"colors": []
},
{
"_id":"5bd6d697975e892464b0ed31",
"shape":"circle",
"colors": []
}
]
}
通过使用此代码:
db.test.aggregate(
{ $match : {
"shapes.shape": "square"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes.shape": "square"
}}
)
它给了我这个结果:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
},
{
"_id":"5bd5ba2ca677cb000469168a",
"shapes":[
{
"_id":"5bd7a9e4604b760004947834",
"shape":"square",
"colors": []
}
]
}
但我想要的是只获取第一个看起来像这样的文档:
{
"_id":"562e7c594c12942f08fe4192",
"shapes":[
{
"_id":"5bd6c4de95ffe03480ee8796",
"shape":"square",
"colors": []
}
]
}
所以我尝试像这样在子文档中使用“_id”属性:
db.test.aggregate(
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}},
{ $unwind : "$shapes" },
{ $match : {
"shapes._id": "5bd6c4de95ffe03480ee8796"
}}
)
但是这样做会返回一个空数组,就像这样:
[]
基本上我想要的是在我的查询中使用特定子文档的“_id”属性,以便我可以在该特定子文档的“颜色”数组上推送一些内容。我应该如何更改我将能够使用“_id”属性的查询语句?
【问题讨论】:
-
在最后使用
$limit阶段db.test.aggregate([ { $match: { "shapes.shape": "square" } }, { $unwind: "$shapes" }, { $match: { "shapes.shape": "square" } }, { $limit: 1 } ]) -
@AnthonyWinzlet 这将是一个很好的解决方法,但是如果我有 10 个这样的文档并且我想在其中一个文档上操作一些东西怎么办?基本上我想要一个特定的文档/子文档,这样我就可以操作它上面的一些数据。我想我对我的问题不是很清楚,所以我编辑了它。如果我的问题不够清楚,我深表歉意。
-
将您的
_id转换为ObjectId。类似mongoose.Types.ObjectId("5bd6c4de95ffe03480ee8796") -
成功了。我明白了,所以 _id 属性的数据类型不仅仅是一个常规字符串,而 mongoose 将“5bd6c4de95ffe03480ee8796”解释为一个常规字符串。可以这样解释吗?