Mongo查询查找键的钥匙阵列本身就是嵌套数组中的一个项目
我的第一个集合如下所示,我正在使用电子邮件搜索文档,并匹配作业阵列中的特定JobID。然后,通过将_id与jobs.process.profile_id匹配来插入第二个集合的文档。
{
"_id": {
"$oid": "6229d3cfdbfc81a8777e4821"
},
"jobs": [
{
"job_ID": {
"$oid": "62289ded8079821eb24760e0"
},
"Process": [
{
"profile_id": {
"$oid": "6285e571681188e83d434797"
}
},
{
"profile_id": {
"$oid": "6285e571681188e83d434799"
}
}
],
},
{
"job_ID": {
"$oid": "6228a252fb4554dd5c48202a"
},
"Process": [
{
"profile_id": {
"$oid": "62861067dc9771331e61df5b"
}
}
],
},
{
"job_ID": {
"$oid": "622af1c391b290d34701af9f"
},
"Process": [
""
],
}
],
"email": "********@gmail.com"
}
我的第二个集合是,我需要通过与jobs.process.profile_id匹配,将此文档插入我的第一个集合中。
{
"_id": {
"$oid": "6285e571681188e83d434797"
},
"Name": "Lakshdwanan",
"Location":"California"
}
我已经尝试了查询,
aggregate([
{ $match: { email: email } },
{
$lookup: {
from: 'user__profiles',
localField: 'jobs.Process.profile_id',
foreignField: '_id',
as: 'jobings',
},
},
{
$addFields: {
jobings: {
$map: {
input: {
$filter: {
input: '$jobs',
as: 'm',
cond: {
$eq: ['$$m.job_ID', objInstance],
},
},
},
as: 'm',
in: {
$mergeObjects: [
{
$arrayElemAt: [
{
$filter: {
input: '$jobings',
cond: {
$eq: ['$$this._id', '$$m.Process.profile_id'],
},
},
},
0,
],
},
'$$m',
],
},
},
},
},
},
{
$project: {
jobings: 1,
_id: 0,
},
},
]);
我的输出应仅根据第一个集合文档匹配显示第二个集合文档。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
edit :如果您只需要特定作业的数据,则最好在
$ filter
$ lookup
步骤之前。$查找
之后,只有$ unvind
和格式:jobs.process.profile_id
是user__profiles
_id,因此无需合并任何东西...结果是user__profiles 收集“按原样”,但可以按想要的格式进行格式化...
_id
可以轻松地重命名profile_id
。EDIT: If you want the data for a specific job only, it is better to
$filter
the jobs before the$lookup
step. After the$lookup
, just$unwind
and format:Playground
The
jobs.Process.profile_id
is theuser__profiles
_id, so no need to merge anything...The results are documents fromuser__profiles
collection "as is" but they can be formatted as wanted..._id
key name can be renamedprofile_id
easily.