如何查询 MongoDB 中的引用字段?
How can I query on a referenced field in MongoDB?
我有两个合集,users
和 posts
。典型文档的相关部分如下所示:
用户
{
"_id": "user1",
"name": "Joe",
"age": 20
}
帖子
{
"content": "Yo what's up!",
"created": "2018-02-05T05:00:00.000Z",
"author": "user1"
}
我想在 returns 以下内容的帖子集合上创建查询:
{
"content": "Yo what's up!",
"created": "2018-02-05T05:00:00.000Z",
"author": {
"name": "Joe",
"age": 20
}
有没有办法在原始 MongoDB 中做到这一点?
我正在使用 MongoDB Node.js 客户端。
将聚合与查找运算符结合使用。
db.posts.aggregate([
{"$lookup":{
"from":"users",
"localField":"author",
"foreignField":"_id",
"as":"author"
}},
{"$addFields":{
"author": {"$arrayElemAt":["$author",0]}
}}])
db.posts.aggregate(
// Pipeline
[
// Stage 1
{
$lookup: {
"from": "user",
"localField": "author",
"foreignField": "_id",
"as": "authorobj"
}
},
// Stage 2
{
$project: {
content: 1,
created: 1,
author: {
'name': {
"$arrayElemAt": ["$authorobj.name", 0]
},
'age': {
"$arrayElemAt": ["$authorobj.age", 0]
}
},
}
},
]
);
我有两个合集,users
和 posts
。典型文档的相关部分如下所示:
用户
{
"_id": "user1",
"name": "Joe",
"age": 20
}
帖子
{
"content": "Yo what's up!",
"created": "2018-02-05T05:00:00.000Z",
"author": "user1"
}
我想在 returns 以下内容的帖子集合上创建查询:
{
"content": "Yo what's up!",
"created": "2018-02-05T05:00:00.000Z",
"author": {
"name": "Joe",
"age": 20
}
有没有办法在原始 MongoDB 中做到这一点? 我正在使用 MongoDB Node.js 客户端。
将聚合与查找运算符结合使用。
db.posts.aggregate([
{"$lookup":{
"from":"users",
"localField":"author",
"foreignField":"_id",
"as":"author"
}},
{"$addFields":{
"author": {"$arrayElemAt":["$author",0]}
}}])
db.posts.aggregate(
// Pipeline
[
// Stage 1
{
$lookup: {
"from": "user",
"localField": "author",
"foreignField": "_id",
"as": "authorobj"
}
},
// Stage 2
{
$project: {
content: 1,
created: 1,
author: {
'name': {
"$arrayElemAt": ["$authorobj.name", 0]
},
'age': {
"$arrayElemAt": ["$authorobj.age", 0]
}
},
}
},
]
);