MongoDB - 跨多个集合组合查询
MongoDB - combining query across mulitple collections
我正在尝试弄清楚如何从本质上在 MongoDB 中进行连接。我读过有关聚合的信息:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/,但这似乎不是我要找的。
我对 NoSQL 也很陌生,所以我不确定我应该在这里使用什么。
我在MongoDB中有两个合集,结构如下:
数据库集合 - 员工:
{
_id: 1,
name: 'John Doe',
filesAccess: {
web: true
},
fileIds: [
'fileId1',
'fileId2'
]
},
{
_id: 2,
name: 'Bob Jones',
filesAccess: {
web: false
},
fileIds: [
'fileId3',
'fileId4'
]
}
数据库集合-文件:
{
_id: fileId1,
fileMetaData: {
location: 'NE'
}
},
{
_id: fileId2,
fileMetaData: {
location: 'NE'
}
},
{
_id: fileId3,
fileMetaData: {
location: 'SW'
}
},
{
_id: fileId4,
fileMetaData: {
location: 'SW'
}
}
我希望能够查询拥有 fileAccess.web = true
的所有员工并获取他们的员工 ID、姓名和 fileMetaData.location
。所有员工文件的 location
都相同。所以查询只需要使用员工的第一个fileId
来从files
集合
中获取location
所以我希望我的结果应该是这样的:
{
_id: 1,
name: 'John Doe',
location: 'NE'
}
在 MongoDB 中,您将如何构建查询来完成此任务?我使用 Studio3T 作为数据库的接口。非常感谢任何帮助
您可以使用此聚合查询:
- 首先
$match
只获取 filesAccess.web
为真的文档。
- 基于
fileIds
和 _id
上的值的联接。这给出了一个调用 result
. 的数组
- 然后获得第一名
- 和
$project
输出你想要的字段。
db.employess.aggregate([
{
"$match": {
"filesAccess.web": true
}
},
{
"$lookup": {
"from": "files",
"localField": "fileIds",
"foreignField": "_id",
"as": "result"
}
},
{
"$set": {
"result": {
"$arrayElemAt": [
"$result",
0
]
}
}
},
{
"$project": {
"_id": 1,
"name": 1,
"location": "$result.fileMetaData.location"
}
}
])
示例here
我正在尝试弄清楚如何从本质上在 MongoDB 中进行连接。我读过有关聚合的信息:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/,但这似乎不是我要找的。
我对 NoSQL 也很陌生,所以我不确定我应该在这里使用什么。
我在MongoDB中有两个合集,结构如下:
数据库集合 - 员工:
{
_id: 1,
name: 'John Doe',
filesAccess: {
web: true
},
fileIds: [
'fileId1',
'fileId2'
]
},
{
_id: 2,
name: 'Bob Jones',
filesAccess: {
web: false
},
fileIds: [
'fileId3',
'fileId4'
]
}
数据库集合-文件:
{
_id: fileId1,
fileMetaData: {
location: 'NE'
}
},
{
_id: fileId2,
fileMetaData: {
location: 'NE'
}
},
{
_id: fileId3,
fileMetaData: {
location: 'SW'
}
},
{
_id: fileId4,
fileMetaData: {
location: 'SW'
}
}
我希望能够查询拥有 fileAccess.web = true
的所有员工并获取他们的员工 ID、姓名和 fileMetaData.location
。所有员工文件的 location
都相同。所以查询只需要使用员工的第一个fileId
来从files
集合
location
所以我希望我的结果应该是这样的:
{
_id: 1,
name: 'John Doe',
location: 'NE'
}
在 MongoDB 中,您将如何构建查询来完成此任务?我使用 Studio3T 作为数据库的接口。非常感谢任何帮助
您可以使用此聚合查询:
- 首先
$match
只获取filesAccess.web
为真的文档。 - 基于
fileIds
和_id
上的值的联接。这给出了一个调用result
. 的数组
- 然后获得第一名
- 和
$project
输出你想要的字段。
db.employess.aggregate([
{
"$match": {
"filesAccess.web": true
}
},
{
"$lookup": {
"from": "files",
"localField": "fileIds",
"foreignField": "_id",
"as": "result"
}
},
{
"$set": {
"result": {
"$arrayElemAt": [
"$result",
0
]
}
}
},
{
"$project": {
"_id": 1,
"name": 1,
"location": "$result.fileMetaData.location"
}
}
])
示例here