gpt4 book ai didi

node.js - 查询依赖数组大小与某个值匹配的文档

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:55 25 4
gpt4 key购买 nike

我有以下架构:

Collection1
name
slug
Collection2
name
slugCollection1

Collection1Collection2 之间的“链接”是通过字段 slugslugCollection1 实现的。

我尝试使用 MongoDB 的聚合框架实现一个请求,以获取具有特定名称的 Collection1 的所有元素以及 Collection2 类型的依赖元素的数量。

我可以利用$project获得提示:

[
{
"$lookup": {
"from": "Collection2",
"localField": "slug",
"foreignField": "slugCollection1",
"as": "elements"
}
},
{
"$project": {
"_id": 0,
"id": "$id",
"name": 1,
"slug": 1,
"elementsNumber": {
"$size": "$elements"
}
}
}
]

但稍后我无法将 elementsNumber 字段用于 $match 中。我猜这是因为它不是 Collection1 的字段部分。

有没有办法实现这样的查询?谢谢!

最佳答案

您当然可以使用 $match 使用给定条件过滤文档的管道:

[
{
"$lookup": {
"from": "Collection2",
"localField": "slug",
"foreignField": "slugCollection1",
"as": "elements"
}
},
{
"$project": {
"_id": 0,
"id": "$id",
"name": 1,
"slug": 1,
"elementsNumber": { "$size": "$elements" }
}
},
{ "$match": { "elementsNumber": { "$gt": 3 } } }
]

关于node.js - 查询依赖数组大小与某个值匹配的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536448/

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