我的mongodb系列看起来像这样:
{
"_id" : ObjectId("5333bf6b2988dc2230c9c924"),
"name" : "Mongo2",
"notes" : [
{
"title" : "mongodb1",
"content" : "mongo content1"
},
{
"title" : "replicaset1",
"content" : "replca content1"
}
]
}
{
"_id" : ObjectId("5333fd402988dc2230c9c925"),
"name" : "Mongo2",
"notes" : [
{
"title" : "mongodb2",
"content" : "mongo content2"
},
{
"title" : "replicaset1",
"content" : "replca content1"
},
{
"title" : "mongodb2",
"content" : "mongo content3"
}
]
}
我只想查询标题为“mongodb2”但不想要完整文档的注释。 我使用以下查询:
> db.test.find({ 'notes.title': 'mongodb2' }, {'notes.$': 1}).pretty()
{
"_id" : ObjectId("5333fd402988dc2230c9c925"),
"notes" : [
{
"title" : "mongodb2",
"content" : "mongo bakwas2"
}
]
}
我期待它返回两个标题为“mongodb2”的音符。 当我们在文档中查询文档时,mongo是否仅返回第一个文档?
答案 0 :(得分:1)
$
始终引用第一个匹配,$elemMatch
投影运算符也是如此。
我认为你有三种选择:
$match
和$project
)我可能会选择选项1,但您可能有数据模型的原因。
答案 1 :(得分:1)
positional $
运算符只能返回找到的第一个匹配索引。
使用aggregate:
db.test.aggregate([
// Match only the valid documents to narrow down
{ "$match": { "notes.title": "mongodb2" } },
// Unwind the array
{ "$unwind": "$notes" },
// Filter just the array
{ "$match": { "notes.title": "mongodb2" } },
// Reform via group
{ "$group": {
"_id": "$_id",
"name": { "$first": "$name" },
"notes": { "$push": "$notes" }
}}
])
因此,您可以使用它来“过滤”数组中的特定文档。