gpt4 book ai didi

node.js - 使用 Mongoose 使用 arrayFilters 查找

转载 作者:可可西里 更新时间:2023-11-01 10:45:55 25 4
gpt4 key购买 nike

我必须过滤评论中仅包含状态 C 的对象(如果至少只有评论具有状态 C,则应单独打印该对象)我尝试使用数组过滤器,但我没有得到准确的结果

 {
"_id" : ObjectId("5b8f84379f432a42383a85bb"),
"projectID" : ObjectId("00000000e614c33390237ce3"),
"inspection_data" : [
{
"locationAspects" : [
{
"aspectname" : "Ground floor",
"comments" : [
{
"status" :"C",
"comment" : [
"good"
],
"_id" : ObjectId("5b8f84379f16400f884d9974")
}
],
"_id" : ObjectId("5b8f84379f16400f884d9975")
},
{
"aspectname" : "Second floor",
"comments" : [
{
"status" :"P",
"comment" : [
"nothing"
],

"_id" : ObjectId("5b8f84379f16400f884d9971")
}
],
"_id" : ObjectId("5b8f84379f16400f884d9972")
},
],
"published_date" : ISODate("2018-09-05T07:22:31.017Z"),
"_id" : ObjectId("5b8f84379f16400f884d9976")
},
{
"locationAspects" : [
{
"aspectname" : "Ground floor",
"comments" : [
{
"status" :"P",
"comment" : [
"good"
],
"_id" : ObjectId("5b8f84379f16400f884d9974")
}
],
"_id" : ObjectId("5b8f84379f16400f884d9975")
}
],
"published_date" : ISODate("2018-09-05T07:22:31.017Z"),
"_id" : ObjectId("5b8f84379f16400f884d9976")
}
]

现在检查数据有两个对象,但一个对象只包含评论状态c,所以应该打印

预期结果

[ {
"locationAspects" : [
{
"aspectname" : "Ground floor",
"comments" : [
{
"status" :"C",
"comment" : [
"good"
],
"_id" : ObjectId("5b8f84379f16400f884d9974")
}
],
"_id" : ObjectId("5b8f84379f16400f884d9975")
},
{
"aspectname" : "Second floor",
"comments" : [
{
"status" :"P",
"comment" : [
"nothing"
],

"_id" : ObjectId("5b8f84379f16400f884d9971")
}
],
"_id" : ObjectId("5b8f84379f16400f884d9972")
},
],
"published_date" : ISODate("2018-09-05T07:22:31.017Z"),
"_id" : ObjectId("5b8f84379f16400f884d9976")
}]

如果至少有一个评论状态为 C,则以上对象只有状态 C,该对象必须单独显示

最佳答案

你需要$filter处理 inspection_data。事情变得复杂,因为你有多层嵌套,所以在你申请之前 $in您需要获取单个 inspection_data 的所有状态的数组。要实现这一点,您可以使用像 "$$data.locationAspects.comments.status" 这样的直接路径,但它会返回一个数组,如下所示:

[ [ "C" ], [ "P" ] ], [ [ "P" ] ] ]

因此您必须展平该数组,这可以使用 $reduce 来实现和 $concatArrays .尝试:

db.col.aggregate([
{ $match: { projectID: ObjectId("00000000e614c33390237ce3") } },
{
$project: {
filtered_inspection_data: {
$filter: {
input: "$inspection_data",
as: "data",
cond: {
$let: {
vars: {
statuses: {
$reduce: {
input: "$$data.locationAspects.comments.status",
initialValue: [],
in: { $concatArrays: [ "$$this", "$$value" ] }
}
}
},
in: { $in: [ "C", "$$statuses" ] }
}
}
}
}
}
}
])

编辑:要匹配 "C""P",您可以使用替换 { $in: [ "C", "$$statuses"] } 包含以下行

{ $or: [ { $in: [ "C", "$$statuses" ] }, { $in: [ "P", "$$statuses" ] } ] }

关于node.js - 使用 Mongoose 使用 arrayFilters 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com