mongodb - Mongo DB 复杂查询
问题描述
我需要一些有关 MongoDB 的帮助。我有 Ex Schema 和 Database 如下:`
结核病:
User:
{
name: { type: String }
image: { type: String }
city: { type: String }
address: [{
index: { type: Number }
district_id: { type: Schema.ObjectId, ref: 'District' }
}]
}
结核病:
District:{
name: { type: String }
code: { type: String }}
示例数据库:
User: [{
_id: '1234'
name: 'Jacky',
image: '',
city: 'Da Nang',
address: [
{
index: 1,
district_id: '12345'
},
{
index: 2,
district_id: '123456'
},
{
index: 3,
district_id: '1234567'
}
]
}]
District: [
{
_id: '12345',
name: 'Hai Chau',
code: 12
},
{
_id: '123455',
name: 'Lien CHieu',
code: 13
},
{
_id: '1234567',
name: 'Cam Le',
code: 14
},
{
_id: '12345678',
name: 'Son Tra',
code: 15
}
]
我如何通过两个选项(disctrict.name && index)选择用户,例如 District.name = 'Lien Chieu' && address.index > 1。
解决方案
您可以尝试以下查询:
db.District.aggregate([
/** filter required doc from district Coll */
{ $match: { name: "Lien CHieu" } },
{
$lookup: {
from: "User",
let: { id: "$_id" },
pipeline: [
/** Basic filter to get matched doc from User Coll */
{ $match: { $expr: { $in: ["$$id", "$address.district_id"] } } },
/** check for criteria */
{
$addFields: {
mappingField: {
$map: {
input: "$address", as: "each", in: {
$and: [{ $gt: ["$$each.index", 1] }, { $eq: ["$$id", "$$each.district_id"] }]
}
}
}
}
},
/** filter required doc from above which matches our criteria & remove added field */
{ $match: { mappingField: true } }, { $project: { mappingField: 0 } }
],
as: "userdata"
}
}
])
测试: MongoDB-游乐场
推荐阅读
- android - 如何使 GridView 滚动流畅?
- html - 圆圈内的图标未对齐中心,浏览器上的水平和垂直对齐正确 < 100%
- vba - ADO 限制表名
- javascript - 使用 javascript 获取 arangodb 的状态 url
- java - java - 我在java中附加子元素后如何保存xml
- python - 通过乘数编辑列,然后用乘数替换列并将文件另存为新的 .txt 文件 -python
- git - 如果重新设置父分支而不是子分支,子分支会发生什么情况?
- php - 如何从WordPress中相同用户角色的用户列表中删除用户名下的查看链接
- redux - AsyncThunkAction 不适合 AnyAction?
- python - 尝试比较文本文件中的多行并通过加入它们来打印