如何在聚合中使用 MongoDB $in
How to use MongoDB $in in aggregation
我正在查询我的 MongoDB collection 个酒店,我需要创建一个 $match
阶段,我只在其中保留至少有一个房间的文件,即匹配每个 $in
我的示例文档 collection:
{
title: "Lorem ipsum",
rooms: [
{
type: "shelter",
spots: 2
},
{
type: "box",
spots: 1
},
{
type: "house",
spots: 5
},
]
}
这个 $match 阶段有效:
{
"rooms.type": {
$in: ["shelter"]
}
"rooms.type": {
$in: ["box"]
}
}
但我无法在 Javascript 中使用两个相同的键创建 object。
所以我需要从我的 NodeJS API 像这样发送它。
但这怎么行不通呢?:
{
$expr: {
$or: [
{ $in: ["$rooms.type", ["shelter"]] },
{ $in: ["$rooms.type", ["box"]] }
]
}
}
如果我没理解错的话,你可以添加一个 $or
阶段来创造这样的条件:
db.collection.aggregate([
{
"$match": {
"$or": [
{
"rooms.type": {"$in": ["shelter","first","array"]}
},
{
"rooms.type": {"$in": ["box","second","array"]}
}
]
}
}
])
此查询将 returns 记录哪些字段 rooms.type
包含存在于两个数组之一中的值。
示例here
我正在查询我的 MongoDB collection 个酒店,我需要创建一个 $match
阶段,我只在其中保留至少有一个房间的文件,即匹配每个 $in
我的示例文档 collection:
{
title: "Lorem ipsum",
rooms: [
{
type: "shelter",
spots: 2
},
{
type: "box",
spots: 1
},
{
type: "house",
spots: 5
},
]
}
这个 $match 阶段有效:
{
"rooms.type": {
$in: ["shelter"]
}
"rooms.type": {
$in: ["box"]
}
}
但我无法在 Javascript 中使用两个相同的键创建 object。 所以我需要从我的 NodeJS API 像这样发送它。 但这怎么行不通呢?:
{
$expr: {
$or: [
{ $in: ["$rooms.type", ["shelter"]] },
{ $in: ["$rooms.type", ["box"]] }
]
}
}
如果我没理解错的话,你可以添加一个 $or
阶段来创造这样的条件:
db.collection.aggregate([
{
"$match": {
"$or": [
{
"rooms.type": {"$in": ["shelter","first","array"]}
},
{
"rooms.type": {"$in": ["box","second","array"]}
}
]
}
}
])
此查询将 returns 记录哪些字段 rooms.type
包含存在于两个数组之一中的值。
示例here