Mongodb 子数组中的搜索
来自数据库的示例文档Mongodb 子数组中的搜索,mongodb,Mongodb,来自数据库的示例文档 { "_id": ObjectId("54f44a657f8b9a1d318b4567"), // other fields "ligaments": [ [ { "data": "dia", "order": 0 }, { "data": "hub", "order": 1 } ], [ { "da
{
"_id": ObjectId("54f44a657f8b9a1d318b4567"),
// other fields
"ligaments": [
[
{
"data": "dia",
"order": 0
},
{
"data": "hub",
"order": 1
}
],
[
{
"data": "pcd",
"order": 0
},
{
"data": "width",
"order": 1
}
]
]
}
我需要找到ligaments字段包含数据的所有条目:“parameter”属性。如何进行此类查询?如果要在嵌套数组中搜索,可以使用$elemMatch运算符:
//returns all the documents that have data equal to 'pcd' or 'width'
db.collection.find({ligaments: {$elemMatch: {$elemMatch: { data: {$in: ['pcd', 'width']}}}}});
如果要指定用户定义的参数,可以通过自定义查询来执行此操作:
//returns all the documents that have data equal to 'parameter'
db.collection.find({ligaments: {$elemMatch: {$elemMatch: { data: 'parameter'}}}});
首先,您的文档结构非常复杂,但如果您想了解输出,请尝试下面的脚本
db.collectionName.aggregate({
"$unwind": "$ligaments"
}, {
"$unwind": "$ligaments"
}, {
"$match": {
"ligaments.data": {
"$in": ["pcd", "width"]
}
}
}, {
"$project": {
"_id": 0,
"ligaments": "$ligaments"
}
})
试试db.collection.find{ligaments.data:'parameter'}?虽然mongodb是无模式的,但这并不意味着你不需要考虑你的模式。好吧,我不纠正你的问题,我需要查找包含一个字段项的所有文档,其中只包含pcd和宽度数据。此查询返回noresults@i.paramonov我想你已经用你的实际收藏更改了我查询中的收藏?我试过运行这个查询,但效果很好。我无法通过这个查询找到,我使用的是mongodb 2.6.6版本。查询返回零results@i.paramonov请将您正在运行的确切查询粘贴到此处,好吗?如果您复制粘贴我的上述查询,它将无法工作,因为集合名称不同。@i.paramonov我已使用MongoDB 2.6.5尝试了此查询,它的工作原理与预期的一样。确保您不只是复制粘贴此查询-您需要用集合名称替换db.collection.find中的集合。