我想在加入時添加多個條件。加入那些滿足以下條件的檔案(同一個集合):
- 有異性
- 有年齡 (IF EXISTS) 介于主要檔案年齡偏好和主要檔案之間有
age(IF EXISTS) 外國檔案偏好(即雙向檢查)
我的嘗試如下,但有兩個問題:
$exists不能在$expridk 中使用,為什么- 年齡查詢是目前的一種方式
$lookup: {
"from": "appusers",
"let": { 'gen': "$gender",'pref': "$preference" },
"pipeline": [{
$match: {$expr: {
$and: [
{ $ne: ["$gender", "$$gen"]},
{ $or: [
{$exists: {"$age": false}},
{$and: [
{ $gte: ["$age", '$$pref.age_from' ] },
{ $lte: [ "$age", '$$pref.age_to' ] }
]}
]}
]
}}}],
"as": "matches"
}
示例:輸入檔案:
{
name: "person1",
age: 36,
gender: "Male",
preference: {
age_from: 25,
age_to: 35
}
}
{
name: "person2",
age: 18,
gender: "Female",
preference: {
age_from: 25,
age_to: 40
}
}
{
name: "person3",
age: 26,
gender: "Female",
preference: {
age_from: 30,
age_to: 35
}
}
{
name: "person4",
age: 26,
gender: "Female",
preference: {
age_from: 30,
age_to: 40
}
}
輸出: 對于第 1 個人,matches 陣列將僅顯示第 4 個人(同樣,第 4 個人匹配將顯示第 1 個人),即:
{
name: person1,
age: 36,
gender: "Male",
preference: {
age_from: 28,
age_to: 35
},
matches: [
{
name: person4,
...
}
]
}
我已經看過這個和這個但沒有幫助
uj5u.com熱心網友回復:
$exists不能在$expridk 中使用,為什么
$expr允許在查詢語言中使用聚合運算式,并且$exists不是聚合運算子,
你只需要糾正兩件事:
- 將
$expr條件放在第一個$and條件中 - 置于
$expr最后$and狀態
db.appusers.aggregate([
{
$lookup: {
from: "appusers",
let: { gen: "$gender", pref: "$preference" },
pipeline: [
{
$match: {
$and: [
{ $expr: { $ne: ["$gender", "$$gen"] } },
{
$or: [
{ age: { $exists: false } },
{
$expr: {
$and: [
{ $gte: ["$age", "$$pref.age_from"] },
{ $lte: ["$age", "$$pref.age_to"] }
]
}
}
]
}
]
}
}
],
as: "matches"
}
}
])
操場
uj5u.com熱心網友回復:
對于$exists問題,你可以用age用$ifNull,并使用$eq以檢查是否存在。
對于 2 路年齡匹配,我認為您只需要為 person4 到 person1 重復從 person1 到 person4 的年齡匹配標準。盡管在您當前給定的測驗用例中,由于 person4 的年齡超出了 person1 的偏好,因此找不到匹配項。
db.appusers.aggregate([
{
"$match": {
name: "person1"
}
},
{
$lookup: {
"from": "appusers",
"let": {
"a": "$age",
"gen": "$gender",
"pref": "$preference"
},
"pipeline": [
{
$match: {
$expr: {
$and: [
{
$ne: [
"$$gen",
"$gender"
]
},
{
$and: [
{
$or: [
{
$eq: [
{
"$ifNull": [
"$age",
"age-not-exists"
]
},
"age-not-exists"
]
},
{
$and: [
{
$gte: [
"$age",
"$$pref.age_from"
]
},
{
$lte: [
"$age",
"$$pref.age_to"
]
}
]
}
]
},
{
$or: [
{
$eq: [
{
"$ifNull": [
"$$a",
"age-not-exists"
]
},
"age-not-exists"
]
},
{
$and: [
{
$gte: [
"$$a",
"$preference.age_from"
]
},
{
$lte: [
"$$a",
"$preference.age_to"
]
}
]
}
]
}
]
}
]
}
}
}
],
"as": "matches"
}
}
])
這是Mongo 游樂場供您參考。
uj5u.com熱心網友回復:
您可以使用 $eq undefined 作為欄位年齡而不是 $exists
{
"from": "appusers",
"let": { 'gen': "$gender",'pref': "$preference" },
"pipeline": [{
$match: {$expr: {
$and: [
{ $ne: ["$gender", "$$gen"]},
{ $or: [
{$eq: ["$age" , undefined]},
{$and: [
{ $gte: ["$age", '$$pref.age_from' ] },
{ $lte: [ "$age", '$$pref.age_to' ] }
]}
]}
]
}}}],
"as": "matches"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/391904.html
標籤:MongoDB 猫鼬 mongodb-查询 聚合框架 聚合
