如果用户 selected_city 也将来自未从 CITY MODEL 选择的城市,如何从用户已经选择的城市键的数组中获取结果
Posted
技术标签:
【中文标题】如果用户 selected_city 也将来自未从 CITY MODEL 选择的城市,如何从用户已经选择的城市键的数组中获取结果【英文标题】: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 【发布时间】:2020-02-21 11:30:11 【问题描述】:城市模型
[
"_id": '1',
"city":'A',
,
"_id": '2',
"city":'B',
,
"_id": '3',
"city":'C',
,
"_id": '4',
"city":'D',
,
"_id": '5',
"city":'E',
]
用户模型
[
"_id": '1',
"user":'sams',
"selected_city":['1','2']
]
希望得到结果
[
"_id": "1",
"user": "sams",
"selected_city": [
"1",
"2"
],
"not_selected": [
"3",
"4",
"5"
]
]
【问题讨论】:
你需要什么输出??输入?? 嗨,山姆,欢迎来到 SO !请添加一些您迄今为止尝试过的代码。 这些输出 "_id": '1',"user":'sams',"selected_city":['1','2'],"not_selected":['3', '4','5'] 我需要这些输出 "_id": '1',"user":'sams',"selected_city":['1','2'],"not_selected":['3 ','4','5'] 【参考方案1】:试试:
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);
【讨论】:
我要mongodb查询【参考方案2】:你可以使用下面的聚合
db.coll2.aggregate([
$lookup:
from: "coll1",
pipeline: [],
as: "cities"
,
$addFields:
not_selected:
$setDifference: [
"$cities._id",
"$selected_city"
]
])
【讨论】:
【参考方案3】:这是开箱即用的方式,
可能会有点小技巧,
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",而 "id" 不存在在users
和cities
集合中,
这样您就可以从cities
集合中为用户获取所有文档。
然后在$project
阶段我使用$filter
过滤掉了结果。
那么对于notSelectedCities
,我使用了 $indexOfArray
运算符,如果 selected_city 中不存在城市,它将返回 -1,并使用 $eq
运算符进行比较使用 -1,然后只选择那个特定的城市。
希望这会有所帮助! :-)
【讨论】:
以上是关于如果用户 selected_city 也将来自未从 CITY MODEL 选择的城市,如何从用户已经选择的城市键的数组中获取结果的主要内容,如果未能解决你的问题,请参考以下文章
Android ViewModel 未从 BackStackEntry 获取选定项