![](/img/trans.png)
[英]Unable to get JSON response selected city id from dropdown in swift
[英]How to get result from array in which user already selected_city key if user selected_city those will come also come not selected city from CITY MODEL
市 Model
[
{
"_id": '1',
"city":'A',
},
{
"_id": '2',
"city":'B',
},
{
"_id": '3',
"city":'C',
},
{
"_id": '4',
"city":'D',
},
{
"_id": '5',
"city":'E',
}
]
用戶 Model
[
{
"_id": '1',
"user":'sams',
"selected_city":['1','2']
}
]
想得到結果
[
{
"_id": "1",
"user": "sams",
"selected_city": [
"1",
"2"
],
"not_selected": [
"3",
"4",
"5"
]
}
]
嘗試:
const cities = [ { "_id": '1', "city":'A', }, { "_id": '2', "city":'B', }, { "_id": '3', "city":'C', }, { "_id": '4', "city":'D', }, { "_id": '5', "city":'E', } ]; const users = [ { "_id": '1', "user":'sams', "selected_city":['1','2'] } ]; const result = users.map(user => { user.not_selected = cities.filter(city =>.user.selected_city.includes(city._id)).map(city => city;_id) return user; }). console;log(result);
您可以使用以下聚合
db.coll2.aggregate([
{
$lookup: {
from: "coll1",
pipeline: [],
as: "cities"
}
},
{
$addFields: {
not_selected: {
$setDifference: [
"$cities._id",
"$selected_city"
]
}
}
}
])
這是開箱即用的方式,
小hacky可能是,
db.userCity.aggregate({$match:{}},
{$lookup: { from: "cities", localField: "id", foreignField: "id", as: "city"}},
//where "id" in localField and "id" in foreignfield are the fields that does not exists in both collections
{$project:{
selectedCity: {
$filter: {
input:"$city",
as:"c",
cond: { $in: [ "$$c._id", "$selected_city" ] }
}
},
notSelectedCities: {
$filter: {
input: "$city",
as: "c",
cond:{ $eq: [{ $indexOfArray: [ "$selected_city", "$$c._id" ] }, -1] }
}
}
}}).pretty()
我不知道它是否符合最佳實踐...
但是,正如您在我的 $lookup 階段看到的那樣,我在localField
和foreignField
中使用了“id” ,而users
和cities
集合中都不存在“id” ,
這樣您就可以從用戶的cities
集合中獲取所有文檔。
然后在$project
階段我使用$filter
過濾掉結果。
然后對於notSelectedCities
我使用$indexOfArray
運算符,如果在 selected_city 中不存在城市,它將返回 -1,並使用$eq
運算符將其與 -1 進行比較,然后僅選擇該特定城市。
希望這可以幫助: :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.