如何在使用go的mongodb查询中将$ or与$ lookup一起使用?

时间:2018-09-12 06:12:28

标签: mongodb go mgo

我想使用$ or和$ lookup从mongodb文档中获取数据记录。 这是我要声明的查询:-

pipeline1 := []bson.M{
    {"$lookup": bson.M{"from": "comment", "localField": "_id", "foreignField": "blog_id", "as": "comments"}},
    {"$addFields": bson.M{"comments": bson.M{"$size": "$comments"}}},
}
pipe1 := getCollection.Pipe(pipeline1)

在上面的查询中,它将首先对记录进行计数,并添加具有特定数据的字段。但是现在查询中有一点变化,就是现在有两个参数我必须使用$或正则表达式进行搜索,我希望函数能够执行相同的操作,但是在获取记录时(如果用户输入)任何参数,它将使用该关键字获取记录并对该数据进行计数。

已编辑

我必须将上面的查询与下面的查询结合起来:-

query["$or"] = []bson.M{
    bson.M{"title": bson.RegEx{"(?i).*" + value + ".*", "i"}},
    bson.M{"type": bson.RegEx{"(?i).*" + value + ".*", "i"}},
    bson.M{"author": bson.RegEx{"(?i).*" + value + ".*", "i"}},
    bson.M{"tags": bson.RegEx{"(?i).*" + value + ".*", "i"}},
}

我正在像这样组合它,但是它什么也没有返回。

pipeline1 := []bson.M{
    {"$or": []bson.M{
        bson.M{"_id": bson.M{"$in": ids}},
        bson.M{"type": bson.RegEx{"(?i).*" + types + ".*", "i"}},
        bson.M{"category": bson.RegEx{"(?i).*" + category + ".*", "i"}},
        bson.M{"author": bson.RegEx{"(?i).*" + keyword + ".*", "i"}},
        bson.M{"title": bson.RegEx{"(?i).*" + keyword + ".*", "i"}},
        bson.M{"tags": bson.RegEx{"(?i).*" + tag + ".*", "i"}}}},
    {"$lookup": bson.M{"from": "comment", "localField": "_id", "foreignField": "blog_id", "as": "comments"}},
    {"$addFields": bson.M{"comments": bson.M{"$size": "$comments"}}},
}
pipe1 := getCollection.Pipe(pipeline1)

最新编辑

AS @kmdreko说我做类似的事情,但是不起作用:-

 query := bson.M{}
query["$or"] = []bson.M{
    bson.M{"_id": bson.M{"$in": ids}},
    bson.M{"type": bson.RegEx{"(?i).*" + types + ".*", "i"}},
    bson.M{"category": bson.RegEx{"(?i).*" + category + ".*", "i"}},
    bson.M{"author": bson.RegEx{"(?i).*" + keyword + ".*", "i"}},
    bson.M{"title": bson.RegEx{"(?i).*" + keyword + ".*", "i"}},
    bson.M{"tags": bson.RegEx{"(?i).*" + tag + ".*", "i"}},
}
fmt.Println(query)
pipeline1 := []bson.M{
    {"$lookup": bson.M{"from": "comment", "localField": "_id", "foreignField": "blog_id", "as": "comments"}},
    {"$addFields": bson.M{"comments": bson.M{"$size": "$comments"}}},
    {"$match": query},
}
fmt.Println(pipeline1)
pipe1 := getCollection.Pipe(pipeline1)

0 个答案:

没有答案