以下是mongodb中的集合
{
"name" : "Tom" ,
"occupation" : "employee" ,
"data" : [
{
"owns" : "Television" ,
"company" : "xyz"
},
{
"owns" : "Television" ,
"company" : "abc"
},
{
"owns" : "laptop" ,
"company" : "abc"
} ,
{
"owns" : "Television" ,
"company" : "xyz"
}
]
}当我问起
db.exp.find({"data.owns" : "Television"}) mongodb返回结果集中有“所有者”:“膝上型计算机”的文档。
当我问起
db.exp.find({"data.owns": "Television"},{_id: 0, data: {$elemMatch: {"owns": "Television"}}}) 结果只显示数据字段中的一个文档,其中找到了“the”的第一次匹配。
如何查询汤姆拥有电视的所有三个文档,不包括膝上型电脑文档。预期结果
[
{
"owns" : "Television" ,
"company" : "xyz"
},
{
"owns" : "Television" ,
"company" : "abc"
},
{
"owns" : "Television" ,
"company" : "xyz"
}
] 注意:在本例中,我只提到了数据字段中的4个文档,其中原始集合有50多个文档。对不起我的英语很差:)。
发布于 2015-03-31 05:56:14
这可以使用aggregation.来完成
data数组。owns值为Television的文档。db.exp.aggregate(
[
{ "$unwind": "$data" },
{ "$match": { "data.owns": "Television" }},
{
"$group": {
"_id": {
"name": "$name",
"occupation": "$occupation"
},
"data": { "$push": "$data" }
}
},
{
"$project": {
"name": "$_id.name",
"occupation": "$_id.occupation",
"data": 1,
"_id": 0
}
}
]
)结果:
{
"data" : [
{
"owns" : "Television",
"company" : "xyz"
},
{
"owns" : "Television",
"company" : "abc"
},
{
"owns" : "Television",
"company" : "xyz"
}
],
"name" : "Tom",
"occupation" : "employee"
}发布于 2015-03-31 05:00:15
假设集合exp中有两个文档
[
{
"name" : "Tom" ,
"occupation" : "employee" ,
"data" : [ { "owns" : "Television" , "company" : "xyz" },
{ "owns" : "Television" , "company" : "abc" },
{ "owns" : "laptop" , "company" : "abc" } ,
{ "owns" : "Television" , "company" : "xyz" } ]
},
{
"name" : "Jerry" ,
"occupation" : "employee" ,
"data" : [ { "owns" : "Mobile" , "company" : "xyz" },
{ "owns" : "Mobile" , "company" : "abc" },
{ "owns" : "laptop" , "company" : "abc" } ,
{ "owns" : "Laptop" , "company" : "xyz" } ]
}
]然后,使用查询db.exp.find({"data.owns" : "Television"}),您将获得
{ "_id" : 101,
"name" : "Tom",
"occupation" : "employee",
"data" : [
{ "owns" : "Television", "company" : "xyz" },
{ "owns" : "Television", "company" : "abc" },
{ "owns" : "laptop", "company" : "abc" },
{ "owns" : "Television", "company" : "xyz" }
]
}由于第一个文档的字段owns等于Television,结果将是完整的第一个文档。(包括具有owns而非Television的字段)第二个文档将不会是结果的一部分,因为它没有任何具有值Television的owns字段。
$elemMatch只返回一个文档。
http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/
如果只希望数组中的这三个对象以Television作为其值,则可以使用游标来存储查询的整个结果(在本例中只有一个文档)。
var x = db.authors.find({"data.owns": "Television"},{_id: 0, "data.owns": 1})现在,使用每个循环只获取具有owns和值Television的文档。
https://stackoverflow.com/questions/29359835
复制相似问题