添加一个$match查询与mongodb查找



我正在从2个集合中提取数据,如本MongoDB游乐场所示。在从第二个集合中提取数据时,我想在tag上创建一个匹配,这样只有那些与特定tag相关联的帖子才会返回。

下面是我创建的查询:
db.Vote.aggregate([
{
$match: {
comment: {
$ne: null,
},
"comment.topic": {
$exists: 1,
$regex: ".",
$options: "i",
},
},
},
{
$group: {
_id: {
topic: "$comment.topic",
text_sentiment: "$comment.text_sentiment",
},
total: {
$sum: 1,
},
postIds: {
$push: "$postId",
},
},
},
{
$group: {
_id: "$_id.topic",
total: {
$sum: "$total",
},
text_sentiments: {
$push: {
k: "$_id.text_sentiment",
v: "$total",
},
},
postIds: {
$push: "$postIds",
},
},
},
{
$project: {
topic: "$_id",
topicOccurance: "$total",
sentiment: {
$arrayToObject: "$text_sentiments",
},
postIds: {
$reduce: {
input: "$postIds",
initialValue: [],
in: {
$concatArrays: ["$$value", "$$this"],
},
},
},
},
},
{
$sort: {
topicOccurance: -1,
},
},
{
$lookup: {
from: "Post",
localField: "postIds",
foreignField: "_id",
as: "tag",
},
},
{
$addFields: {
postIds: {
$setUnion: "$postIds",
},
tag: {
$setUnion: {
$map: {
input: "$tag",
in: "$$this.tag",
},
},
},
},
},
]);

结果类似于:

{
"_id" : "Collaboration & Teamwork",
"topic" : "Collaboration & Teamwork",
"topicOccurance" : 355,
"sentiment" : {
"Negative" : 102,
"Neutral" : 132,
"Positive" : 121
},
"postIds" : [
"0iWc2U8FVz",
"3Qzysi2cXD",
"3hRx7qAvcb",
"BsrTDkHmkE",
"LT2HE2uEa5",
"Qw0WcUBcnY",
"U72zss2Af5",
"V9DcRcSawi",
"hNwFVJ2bBk"
],
"tag" : [
[
"Engagement"
],
[
"Environment"
],
[
"Feedback & Recognition"
],
[
"Leadership"
],
[
"Management"
],
[
"Meaningful Work"
],
[
"Open Text"
]
],
"totalDocs" : 39
}

tag匹配后,响应将只有具有tag = fooPosts。我该怎么做呢?

Mongo DB Playground:这有上面的查询和样例数据。

请将此代码添加到查找中,它应该对您有所帮助

{
$lookup:
{
from: "Post",
let: { tagInit: "$tag", postidInit: "$postIds" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$_id",  "$$postids" ] },
{ $eq: [ "$tag", "$$tagInit" ] }
]
}
}
}
],
as: "tag"
}
}

编辑:如果您希望查询返回匹配标记条件的sentimentpostIds,您可以在早期阶段使用$lookup

db.Vote.aggregate([
{$match: {"comment": {$ne: null},
"comment.topic": {$exists: 1, $regex: ".", $options: "i"}}
},
{$lookup: {
from: "Post",
let: {postId: "$postId"},
pipeline: [
{$match: {$expr: {$and: [{$eq: ["$_id", "$$postId"]}, {$in: ["a", "$tag"]}]}}}
],
as: "tag"
}
},
{$match: {$expr: {$gt: [{$size: "$tag"}, 0]}}},
{$group: {
_id: {topic: "$comment.topic", text_sentiment: "$comment.text_sentiment"},
total: {$sum: 1}, postIds: {$push: "$postId"}}
},
{$group: {
_id: "$_id.topic",
total: {$sum: "$total"},
text_sentiments: {
$push: {k: "$_id.text_sentiment", v: "$total"}},
postIds: {$push: "$postIds"}
}
},
{$project: {
topic: "$_id",
topicOccurance: "$total",
sentiment: {$arrayToObject: "$text_sentiments"},
postIds: {
$reduce: {
input: "$postIds",
initialValue: [],
in: {$concatArrays: ["$$value", "$$this"]}
}
}
}
},
{$sort: {"topicOccurance": -1}},
{$addFields: {postIds: {$setUnion: "$postIds"},
tag: {$setUnion: {$map: {input: "$tag", in: "$$this.tag"}}
}
}
}
])

看看它在操场的例子中是如何工作的

相关内容

  • 没有找到相关文章

最新更新