![](/img/trans.png)
[英]Look up nested arrays of objects for a match by separate criteria on each level
[英]MongoDB query - look up ObjectIDs in nested arrays of objects
我需要在对象的嵌套 arrays 中查找 ObjectID。 这是我到目前为止得到的:
.Shift.aggregate([
{ $match: { startDate: { $gte: lowerDate, $lte: upperDate} } },
{ $group: {_id: '$team', shifts: { $addToSet: '$_id' } } },
{ $lookup: {from: 'teams', localField: '_id', foreignField: '_id', as: 'team' }},
{ $lookup: {from: 'shifts', localField: 'shifts', foreignField: '_id', as: 'shifts' }}])
.exec(function (err, teamShifts) {...
这就是我现在拥有的
[
...
{
"_id": "60a277b05c7462f42b3d788c",
"shifts": [
{
"_id": "60a62116ead409441bd112",
"assignedUser": "60a36baddf6a04c72b2d9f",
"team": "60a277b05c7462f43d788c",
"shiftType": "60a278357462f42b3d7895",
"startDate": 1621641600000,
"endDate": 1622246400000,
"__v": 0
},
{
"_id": "60a679a03525cec3f86949",
"assignedUser":
...
},
...
],
"team": [
{
"_id": "60a277b05c62f42b3d788c",
"name": "a team name",
"owner": "60a26e6c91273a938690b2",
"description": "a description",
}
]
},
...
]
例如,我试图用另一个文档“users”中的“_id”填充“assignedUser”
但是添加它不会产生我需要的结果:
{ $lookup: {from: 'users', localField: 'shifts.assignedUser', foreignField: '_id', as: 'shifts.assignedUser' }},
我需要做什么来查找/填充嵌套在数据中的 ID?
我尝试放松,但这使得按团队分组变得更加困难,而且在我阅读时不再需要这样做(我们正在运行 mongodb 4.4.3)。 我可能需要 piplines(?),但我无法为我的案例使用文档。
要通过 mongodb 中的一系列文档进行搜索, elemMatch可以让您的生活更轻松。 与您的问题相关的搜索和_id应该这样写:
{ $lookup: {from: 'users', localField: shifts:{$elemMatch:{_id://idvalue_here}},
foreignField: '_id', as:'shifts.$.assignedUser'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.