2017-04-11 191 views
1

我是新来蒙戈,我期待实现使用氧化镁司机转到一个面搜索。我需要获得符合我的查询以及方面计数的文档。与小蒙戈搜索结果计数

我目前的执行是执行查询来获取文件,然后用同样的参数,以获得小计数另一个查询,但似乎真的效率低下。是否有一个很好的方法来一步完成此操作?

举例来说,如果我有藏书:

[{ 
    title: "Book One", 
    author: "Author A", 
    numPages: 20, 
    type: "book" 
}, 
{ 
    title: "Book Two", 
    author: "Author B", 
    numPages: 40, 
    type: "book" 
}, 
... 
... 
... 
{ 
    title: "Magazine AA", 
    author: "Author A", 
    numPages: 10, 
    type: "magazine" 
}] 

首先,我得符合我的查询文件:

err = books.Find(bson.M{"$and": matches}).All(&results) 

然后我重复使用聚合管道和$查询方面得到方面计数:

err = Pipe([]bson.M{ 
    {"$match": bson.M{"$and": matches}}, 
    {"$facet": bson.M{ 
     "type":  []bson.M{bson.M{"$sortByCount": "$type"}}, 
     "author": []bson.M{bson.M{"$sortByCount": "$author"}, 
    }}, 
}).All(&facets) 

我也看到了美元,这将让我写我的结果到一个临时集合,然后我可以用它来确定方面的数量,但我不知道这是否更有效。

回答

1

是否有一个步骤做到这一点的好办法?

是的,您可以使用方面搜索来添加无结果的结果。例如:

pipeline := []bson.M{ 
       {"$match": bson.M{"type": bson.M{"$in": []string{"book", "magazine"}}}}, 
       {"$facet": bson.M{"type": []bson.M{{"$sortByCount":"$type"}}, 
            "author": []bson.M{{"$sortByCount":"$author"}}, 
            "unfaceted": []bson.M{{"$match": bson.M{} }}, 
           }, 
          }, 
      } 
err = collection.Pipe(pipeline).All(&resp) 

上面unfaceted$match是无条件(空),如在第一$match阶段将已经渗透到的文件所需的子集。

它给你下面的结果:

{ 
    "type": [ 
    { 
     "_id": "book", 
     "count": 2 
    }, 
    { 
     "_id": "magazine", 
     "count": 1 
    } 
    ], 
    "author": [ 
    { 
     "_id": "Author A", 
     "count": 2 
    }, 
    { 
     "_id": "Author B", 
     "count": 1 
    } 
    ], 
    "unfaceted": [ 
    { 
     "_id": ObjectId(".."), 
     "title": "Magazine AA", 
     "author": "Author A", 
     "numPages": 10, 
     "type": "magazine" 
    }, 
    { 
     "_id": ObjectId(".."), 
     "title": "Book Two", 
     "author": "Author B", 
     "numPages": 40, 
     "type": "book" 
    }, 
    { 
     "_id": ObjectId(".."), 
     "title": "Book One", 
     "author": "Author A", 
     "numPages": 20, 
     "type": "book" 
    } 
    ] 
} 

现在,你可以通过unfaceted部分重复发送一个单独的查询,而不是。有关操作员的更多示例和说明,另请参阅$facet

+0

太好了!非常感谢你。 – user3476370