mongodb $lookup with foreignfield _id



我想使用$lookup获取结果,该$lookup将本地字段作为_id的数组作为字符串。但这并没有发生。我也尝试过使用_id.str,但仍然没有结果。

db.posts.aggregate([
{
$addFields: {
TagCount: { $size: "$tags" }
}
},
{
$lookup:
{
from: "tags",
localField: "tags",
foreignField: "_id",
as: "tagList"
}
},
]));

收集后的模式

const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 10,
set: v => v.replace(/ss+/gi, ' '),
get: v => { console.log(v); return v.replace(/ss+/gi, ' '); }
},
content: {
type: String,
required: true
},
headerImage: {
type: String
},
tags: [{
type: mongoose.Schema.Types.ObjectId,
required: true,
validate: {
validator: function (v) {
return v.length > 0;
}
},
message: 'There must be one tag',
ref: 'tags'
}],
creationDate: { type: Date, default: Date.now }
});

这是标签架构集合

const tagSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 3,
set: value => value.replace(/ss+/gi, ' '),
get: value => value.replace(/ss+/gi, ' ')
},
description: {
type: String
},
creationDate: {
type: Date,
default: Date.now
}  
}, {
collection: 'tags'
});

此外,我尝试了其他StackOverflow问题,但没有找到任何解决方案。

tags数组的架构定义中包含ref: 'tags'会使mongoose将值存储为DBRef,而不是ObjectID。

如果您打算使用populate函数在客户端检索标记文档,这将非常有用。

聚合中的字段名是$id$ref$db,当使用点符号时,它们不是有效的字段名,就像在聚合管道中需要做的那样。

您可以将每个对象转换为一个数组,这将使其看起来像[ {"k":"$id", v:ObjectId("...")}, {"k":"$ref","v":"tags"}, {"k":"$db","v":"dbname"}]

然后过滤$id键,保留相应的值,并将该数组用作本地字段。

db.posts.aggregate([
{$addFields: {
TagCount: {$size: "$tags"},
tag_ids: {
$map: {
input: "$tags",
as: "dbref",
in: {
$reduce: {
input: {$objectToArray: "$$dbref"},
initialValue: [],
in: {
$cond: {
if: {$eq: ["$$this.k",{$literal: "$id"}]},
then: "$$this.v",
else: "$$value"
}
}
}
}
}
}
}},
{
$lookup: {
from: "tags",
as: "tag_list",
localField: "tag_ids",
foreignField: "_id"
}
}
])
db.posts.aggregate([
{
$lookup: { 
from: "tags",
let: { pid: "$tags" },
pipeline: [
{
$match: {
$expr: {
$eq: ["$_id", { $toObjectId: "$$pid" }]
}
}
}
],
as: "tagList"
}]);

最新更新