我有一個這樣的架構:
parentId: Number
name:[
new Schema({
language: { type: String, enum: ['en-US', 'fr-CA'] },
text: String,
},{ _id: false }
);
],
isActive: Boolean
...
和示例資料如下:
{
parentId:1,
"name": [
{"language": "en-US", "text": "Book"},
{"language": "fr-CA", "text": "livre"}
],
isActive:true
// and so many other fields
},
{
parentId:1,
"name": [
{"language": "en-US", "text": "Pen"}
],
isActive:true
// and so many other fields
}
我的貓鼬搜索法語文本:
db.langs.find({
"name.language":"fr-CA", parentId: 1
})
一季度。我怎樣才能像這樣用法語回傳名字:
{
parentId:1,
"name": "livre",
isActive:true
// and so many other fields
}
Q2。貓鼬有沒有可能回傳法語文本,如果法語不在那里,它會回傳英語?
{
parentId:1,
"name": "livre",
isActive:true
// and so many other fields
},
{
parentId:1,
"name": "pen",
isActive:true
// and so many other fields
}
uj5u.com熱心網友回復:
問題 1:
您可以使用$unwind來解構陣列和$match像一個物件。并且至少用所需的值$addFields覆寫name欄位(如果有多個欄位是比 use 更好的選擇$project)。所有這些都在這樣的聚合管道中:
db.collection.aggregate([
{
"$match": {
"parentId": 1
}
},
{
"$unwind": "$name"
},
{
"$match": {
"name.language": "fr-CA"
}
},
{
"$addFields": {
"name": "$name.text"
}
}
])
示例在這里
問題2:
您可以使用$facet創建“兩種方式”。一個如果存在法國結果,另一個如果不存在。然后檢查是否存在以輸出一個或另一個這樣的值:
db.collection.aggregate([
{
"$match": {
"parentId": 1
}
},
{
"$unwind": "$name"
},
{
"$facet": {
"french": [
{
"$match": {
"name.language": "fr-CA"
}
}
],
"notFrench": [
{
"$match": {
"name.language": "en-US"
}
}
]
}
},
{
"$project": {
"result": {
"$cond": {
"if": {
"$eq": [
{
"$size": "$french"
},
0
]
},
"then": "$notFrench",
"else": "$french"
}
}
}
}
])
示例在這里
uj5u.com熱心網友回復:
你也可以用陣列操作來做到這一點。
查詢1
- 匹配父項 1
- fitler 只保留法語,并取
text - 匹配名稱(洗掉沒有法語書籍的檔案)
測驗代碼在這里
aggregate(
[{"$match": {"parentId": {"$eq": 1}}},
{"$set":
{"name":
{"$getField":
{"field": "text",
"input":
{"$arrayElemAt":
[{"$filter":
{"input": "$name",
"cond": {"$eq": ["$$this.language", "fr-CA"]}}},
0]}}}}},
{"$match": {"$expr": {"$eq": [{"$type": "$name"}, "string"]}}}])
查詢2
- 匹配父項 1
- 降低
- 如果值(我之前找到它)法語我保留它
- 否則如果當前是法國我保留這個
- 否則如果當前是我們我保留這個
- else 值(保留為空的初始值 {})
- 匹配名稱(洗掉沒有法語或美國書籍的檔案)
測驗代碼在這里
aggregate(
[{"$match": {"parentId": {"$eq": 1}}},
{"$set":
{"name":
{"$getField":
{"field": "text",
"input":
{"$reduce":
{"input": "$name",
"initialValue": {},
"in":
{"$switch":
{"branches":
[{"case": {"$eq": ["$$value.language", "fr-CA"]},
"then": "$$value"},
{"case": {"$eq": ["$$this.language", "fr-CA"]},
"then": "$$this"},
{"case": {"$eq": ["$$this.language", "en-US"]},
"then": "$$this"}],
"default": "$$value"}}}}}}}},
{"$match": {"$expr": {"$eq": [{"$type": "$name"}, "string"]}}}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/354587.html
標籤:javascript 节点.js MongoDB 猫鼬 聚合框架
