如何在mongodb中进行查找内部的查询
我在Mongodb中有如下文档 我还有另一份和下面一样的文件 当我创建client.find{id:3,键入:'member'}时,我想得到一个在find中自动查找vatInfo的函数 我应该如何对此发现进行汇总?我不想做双重发现。如何在mongodb中进行查找内部的查询,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我在Mongodb中有如下文档 我还有另一份和下面一样的文件 当我创建client.find{id:3,键入:'member'}时,我想得到一个在find中自动查找vatInfo的函数 我应该如何对此发现进行汇总?我不想做双重发现。 非常感谢您阅读 要添加另一个文档的字段,您可以使用在Mongoose中填充: 要使其工作,您需要在模式中客户机文档和父文档之间有一个引用: const clientSchema = Schema({ [...] parentId: { type: Schem
非常感谢您阅读 要添加另一个文档的字段,您可以使用在Mongoose中填充: 要使其工作,您需要在模式中客户机文档和父文档之间有一个引用:
const clientSchema = Schema({
[...]
parentId: { type: Schema.Types.ObjectId, ref: 'ParentCollection' }
});
然后,您可以在代码中的任意位置使用“填充”:
client.findOne({id: 3, type: 'member'}).populate('parentId');
您可以为此使用聚合管道 -查找父文档 -加入其他集合中的文档 -修改结果的结构
// collection `client`
{
"vatInfo":{ "company": "apple" },
"type": "manager",
"parent": "123"
},
{
"type": "member",
"parentId": "123",
"id": "3"
}
// query example
db.getCollection('client').aggregate([
{ $match: { 'id': '3', 'type': 'member' } },
{
$lookup: {
from: 'client',
localField: 'parentId',
foreignField: 'parent',
as: 't01'
}
},
{
$project: {
'_id': 0,
'type': 1,
'parentId': 1,
'id': 1,
'vatInfo': { $arrayElemAt: [ "$t01.vatInfo", 0 ] }
}
}
])
// result
{
"type" : "member",
"parentId" : "123",
"id" : "3",
"vatInfo" : {
"company" : "apple"
}
}
据我所知,这两份文件都在同一个收藏中。@SuleymanSah感谢你注意到我不知何故遗漏了它,我已经更新了我的答案
const clientSchema = Schema({
[...]
parentId: { type: Schema.Types.ObjectId, ref: 'ParentCollection' }
});
client.findOne({id: 3, type: 'member'}).populate('parentId');
// collection `client`
{
"vatInfo":{ "company": "apple" },
"type": "manager",
"parent": "123"
},
{
"type": "member",
"parentId": "123",
"id": "3"
}
// query example
db.getCollection('client').aggregate([
{ $match: { 'id': '3', 'type': 'member' } },
{
$lookup: {
from: 'client',
localField: 'parentId',
foreignField: 'parent',
as: 't01'
}
},
{
$project: {
'_id': 0,
'type': 1,
'parentId': 1,
'id': 1,
'vatInfo': { $arrayElemAt: [ "$t01.vatInfo", 0 ] }
}
}
])
// result
{
"type" : "member",
"parentId" : "123",
"id" : "3",
"vatInfo" : {
"company" : "apple"
}
}