기본 컬렉션은 User 이며 경험 세부 정보 및 기타 항목 이있는 사용자 프로필 컬렉션이 있습니다. 또한 스킬 컬렉션이 있습니다.
사용자
[{
"_id": "5f1eef8ec68d306fbbf13b0f",
"name": "John Davis",
"email": "[email protected]",
"__v": 0
},
{
"_id": "9q1eef8ec68d306fbbf13bh6",
"name": "Mik Luca",
"email": "[email protected]",
"__v": 0
}]
유저 프로필
[{
"_id": "5f1eef8ec68d306fbbf13b10",
"other_skills": [
null
],
"user_id": "5f1eef8ec68d306fbbf13b0f",
"phone_number": "1234569870",
"location": "5f16b72617fee02922688751",
"primary_skills": [
{
"_id": "5f32635cf764cc40447503a6",
"years": 1,
"skill_id": "5f0da75907a96c3040b3667d"
}
]
},
{
"_id": "5f1eef8ec68d306fbbf13b10",
"other_skills": [
null
],
"user_id": "9q1eef8ec68d306fbbf13bh6",
"phone_number": "1234569870",
"location": "5f16b72617fee02922688751",
"primary_skills": [
{
"_id": "6s0da75907a96c3040b36690",
"years": 1,
"skill_id": "5f0da75907a96c3040b3667d"
}
]
}]
기술
[{
"_id": "5f0da75907a96c3040b3667d",
"skill": "Mongo"
},
{
"_id": "6s0da75907a96c3040b36690",
"skill": "Node"
}]
사용자 프로필 정보와 함께 사용자를 나열하고 기술로도 필터링해야합니다.
나는 시도했다
db.getCollection("users").aggregate(
[
{
"$project" : {
"_id" : NumberInt(0),
"users" : "$$ROOT"
}
},
{
"$lookup" : {
"localField" : "users._id",
"from" : "userprofiles",
"foreignField" : "user_id",
"as" : "userprofiles"
}
},
{
"$unwind" : {
"path" : "$userprofiles",
"preserveNullAndEmptyArrays" : true
}
},
{
"$lookup" : {
"localField" : "userprofiles.primary_skills.skill_id",
"from" : "skills",
"foreignField" : "_id",
"as" : "skills"
}
},
{
"$unwind" : {
"path" : "$skills",
"preserveNullAndEmptyArrays" : true
}
},
{
"$match" : {
"skills._id" : ObjectId("5f0dce8d07a96c3040b36687")
}
}
],
{
"allowDiskUse" : true
}
);
그러나 적절한 결과를 얻지 못했습니다.
사용자 목록으로 사용자 프로필 및 기술 정보를 채우고 기술 ID로 사용자 목록을 필터링하려면 어떻게해야합니까?
인사와 감사합니다.
파이프 라인으로 조회를 사용하여 조회 내에서 필터를 일치시킬 수 있습니다.
$lookup
와 userProfile
수집$match
프로필 ID와 일치하는 파이프 라인skill_id
여기에 일치 와 같은 프로필에 대한 다른 필터$unwind
해체 primary_skills
우리가 skill_id에 조회하려고하기 때문에 배열을$lookup
윌 skills
컬렉션$unwind
primary_skills.skill_id
배열을 객체로 필요하기 때문에 분해$grpup
primary_skills
배열 재구성$match
userProfiles
비어 있지 않은 경우[]
db.users.aggregate([
{
$lookup: {
from: "usersProfile",
let: { id: "$_id" },
as: "userProfiles",
pipeline: [
{
$match: {
$expr: { $eq: ["$$id", "$user_id"] },
// match here user profile filters
"primary_skills.skill_id": "5f0da75907a96c3040b3667d"
}
},
{ $unwind: "$primary_skills" },
{
$lookup: {
from: "skills",
localField: "primary_skills.skill_id",
foreignField: "_id",
as: "primary_skills.skill_id"
}
},
{ $unwind: "$primary_skills.skill_id" },
{
$group: {
_id: "$_id",
other_skills: { $first: "$other_skills" },
phone_number: { $first: "$phone_number" },
location: { $first: "$location" },
primary_skills: {
$push: {
_id: "$primary_skills._id",
skill: "$primary_skills.skill_id.skill",
years: "$primary_skills.years"
}
}
}
}
]
}
},
{ $match: { userProfiles: { $ne: [] } } }
])
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다