你能在mongodb中找到嵌入文档中的特定字段和非特定字段吗?

时间:2016-11-30 14:19:05

标签: mongodb mongodb-query

我有嵌入文件,如

{ a: 
     { aa: { aaa: 1, bbb: 2, ccc: 3 },
       bb: { aaa: 1, bbb: 2, ccc: 3 },
       cc: { aaa: 1, bbb: 2, ccc: 3 }
     }
}

如何编写像:

这样的字段过滤器
find({}, { "a.*.aaa": 1 } )

* = aa, bb, cc

在mongodb文档中没有提示(参见https://docs.mongodb.com/v3.2/tutorial/project-fields-from-query-results/

1 个答案:

答案 0 :(得分:1)

如果您要查询价值,可以这样做。但你正在尝试的是关键。我们必须在密钥上给出完全匹配。

我们可以使用$regex来匹配值,而不是键。

让我们有一个集合

db.collection.find();
{ "_id" : ObjectId("583eed6c911c8e111fb99bf4"), "name" : "a.aa.aaa" }
{ "_id" : ObjectId("583eed72911c8e111fb99bf5"), "name" : "a.bb.aaa" }
{ "_id" : ObjectId("583eed77911c8e111fb99bf6"), "name" : "a.bb.bbb" }
{ "_id" : ObjectId("583eed7b911c8e111fb99bf7"), "name" : "a.cc.bbb" }
{ "_id" : ObjectId("583eed7f911c8e111fb99bf8"), "name" : "a.cc.aaa" }
{ "_id" : ObjectId("583eed84911c8e111fb99bf9"), "name" : "a.cc.bbb" }
{ "_id" : ObjectId("583eed88911c8e111fb99bfa"), "name" : "a.cc.ccc" }
{ "_id" : ObjectId("583eed9a911c8e111fb99bfb"), "name" : "a.aa.ccc" }
{ "_id" : ObjectId("583eeda4911c8e111fb99bfc"), "name" : "a.aa.bbb" }
{ "_id" : ObjectId("583eedfd911c8e111fb99bfd"), "name" : "a.aa.abc" }
{ "_id" : ObjectId("583eee03911c8e111fb99bfe"), "name" : "a.bb.abc" }
{ "_id" : ObjectId("583eee06911c8e111fb99bff"), "name" : "a.cc.abc" }

然后使用$ regex的查询就像

db.collection.find({name:{$regex: /a.*.aa*/}});

以及此查询的结果

{ "_id" : ObjectId("583eed6c911c8e111fb99bf4"), "name" : "a.aa.aaa" }
{ "_id" : ObjectId("583eed72911c8e111fb99bf5"), "name" : "a.bb.aaa" }
{ "_id" : ObjectId("583eed7f911c8e111fb99bf8"), "name" : "a.cc.aaa" }
{ "_id" : ObjectId("583eed9a911c8e111fb99bfb"), "name" : "a.aa.ccc" }
{ "_id" : ObjectId("583eeda4911c8e111fb99bfc"), "name" : "a.aa.bbb" }
{ "_id" : ObjectId("583eedfd911c8e111fb99bfd"), "name" : "a.aa.abc" }
{ "_id" : ObjectId("583eee03911c8e111fb99bfe"), "name" : "a.bb.abc" }
{ "_id" : ObjectId("583eee06911c8e111fb99bff"), "name" : "a.cc.abc" }

请参阅:Mongodb - regex match of keys for subobjects

希望它有帮助!