如何根据嵌套字段值过滤 mongo 集合?

chi*_*imo 2 mongodb meteor mongodb-query

我有一个具有以下结构的流星集合。这实际上来自 的一个Meteor-files集合ostrio

{
 "_id" : "HsXoZ6bxkx5kMcJtm", 
"name" : "trees.jpg", 
"meta" : { "artist_id" : "QkmYdsZsMmRzqTg58" , "artist": "some name"}, 
"mime-type" : "audio/mp3", 
"userId" : "QkmYdsZsMmRzqTg58", 
"_collectionName" : "images" 
}
Run Code Online (Sandbox Code Playgroud)

我定义一个出版物

Meteor.publish('files.artist', function publishUserImages(){
   return Images.find({meta: {artist_id: this.userId}).cursor;
});
Run Code Online (Sandbox Code Playgroud)

我想过滤键meta,返回所有带有artist_id. 我当前的过滤器将仅获取meta具有确切值的那些图像{artist_id: "QkmYdsZsMmRzqTg58"}。过滤器不会返回上面显示的项目,因为它的meta值有一个额外的键artist

如何构建合适的过滤器?

mic*_*ckl 5

您可以使用点符号来查询嵌套字段

Meteor.publish('files.artist', function publishUserImages(){
   return Images.find({ 'meta.artist_id': this.userId}).cursor;
});
Run Code Online (Sandbox Code Playgroud)

区别在于,您的查询需要整个子文档匹配,而使用点表示法您只需检查一个子字段是否相等。