我在MongoDB中使用包含子文档的集合的$运算符时遇到了问题。我正在使用Meteor,我有一个看起来像这样的集合:
{
"_id": "A",
"data_fields": [
{name: "artist", value: "Nirvana"},
{name: "album", value: "Smells Like"},
{name: "random_fieldname1", value: "random_value1"},
]
},
{
"_id": "B",
"data_fields": [
{name: "artist", value: "The Strokes"},
{name: "album", value: "Room on Fire"},
{name: "random_fieldname2", value: "random_value2"},
]
}
我想创建一个查询,将字符串与“艺术家”或“相册”,和对应的值匹配,以仅返回这两个字段(不是示例中的“随机”字段)上文)。
例如,如果我输入“nirvana”或“闻起来像”,输出应如下:
{
"_id": "A",
"data_fields": [
{name: "artist", value: "Nirvana"},
{name: "album", value: "Smells Like"},
]
}
(注意,name =“random_fieldname1”的数组元素不应该在输出中。)
这可能吗?如果可能的话,我宁愿避免使用聚合框架。
非常感谢你。
答案 0 :(得分:1)
以下查询将仅返回匹配的子文档
db.aaa.find({"data_fields.value":"Nirvana"},{"data_fields.$":1})
考虑我在mongodb中有以下内容
{
"_id" : "A",
"data_fields" : [
{
"name" : "artist",
"value" : "Nirvana"
},
{
"name" : "album",
"value" : "Smells Like"
},
{
"name" : "random_fieldname1",
"value" : "random_value1"
}
]
}
{
"_id" : "B",
"data_fields" : [
{
"name" : "artist",
"value" : "The Strokes"
},
{
"name" : "album",
"value" : "Room on Fire"
},
{
"name" : "random_fieldname2",
"value" : "random_value2"
}
]
}
并执行上述查询将返回我:
{
"_id" : "A",
"data_fields" : [
{ "name" : "artist",
"value" : "Nirvana" } ]
}