mongodb - 如何使用 match 子句匹配 mongo 中的嵌套字段?
问题描述
我正在尝试匹配 mongo 文档中的嵌套字段,但我的查询不起作用。
配置:
[
{
linenumber: "car",
type: "004",
nested: {
info: {
subinfo: "B"
}
},
},
{
linenumber: "car",
type: "005",
nested: {
info: {
subinfo: "G"
}
},
}
]
询问:
db.collection.aggregate([
{
$match: {
$and: [
{
linenumber: "car"
},
{
nested: {
info: {
subinfo: {
$in: [
"B",
"G"
]
}
}
}
}
]
}
},
{
$group: {
_id: null,
types: {
$addToSet: "$type"
}
}
}
])
我正在使用 mongoplayground 进行测试。这是链接: https ://mongoplayground.net/p/nND59iO1339
我没有找到任何文件。
解决方案
你快到了。您需要使用点表示法。
db.collection.aggregate([
{
$match: {
$and: [
{
linenumber: "car"
},
{
"nested.info.subinfo": { //Dot notation
$in: [
"B",
"G"
]
}
}
]
}
},
{
$group: {
_id: null,
types: {
$addToSet: "$type"
}
}
}
])
推荐阅读
- stata - 用抽样权重计算观测数
- javascript - 如何通过 ctrl + enter 将 br(换行符)添加到 contenteditable div?
- python - Python模拟类属性
- javascript - nextjs 向组件传递数据
- safari - 网页如何向 Safari Web 扩展发送消息?
- android - 如何将值传递给 post 请求的改造 url
- javascript - 显示符合 Javascript 条件的 HTML 文本?
- rider - 将文件永久绑定到 Rider 中的特定更改列表
- kotlin - 我可以指示 Kotlin 关联第一个元素而不是匹配键提取器的最后一个元素吗?
- windows-10 - 计算机锁定后无法再获取屏幕截图