与多个字段和 mongodb 中的 where 条件不同

2024-01-22

我想写一个相当于distinct and where in mongodb。 SQL查询是select DISTINCT key,score from GPC where note="test2" and notetwo = "meet2"

{ "_id" : ObjectId("4dc86fef6a0aa8513ab5f21c"), "key" : "SAGAR","score" : 16, "note" : "test1", "notetwo" : "meet1" } 
{ "_id" : ObjectId("4dc86ffd6a0aa8513ab5f21d"), "key" : "SAGAR456", "score" : 17, "note" : "testjh1", "notetwo" : "meetjh1" } 
{ "_id" : ObjectId("4dc8700b6a0aa8513ab5f21e"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc871686a0aa8513ab5f21f"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc871696a0aa8513ab5f220"), "key" : "SAGAR33", "score" : 37, "note" : "test2", "notetwo" : "meet2" } 
{ "_id" : ObjectId("4dc8716c6a0aa8513ab5f221"), "key" : "SAGAR456", "score" : 17, "note" : "testjh1", "notetwo" : "meetjh1" } 

查询的预期结果是

[{“键”:“SAGAR33”,“分数”:37}]

等效查询是什么mongodb。我正在使用猫鼬来执行查询。


您需要使用aggregate http://docs.mongodb.org/manual/reference/method/db.collection.aggregate/查询以实现此目的。下面是一个在 shell 中运行的示例(可以很容易地转换为 Mongoose):

db.gpc.aggregate([
    // your where clause: note="test2" and notetwo = "meet2"
    {"$match" : {note:"test2", notetwo:"meet2"}}, 
    // group by key, score to get distinct
    {"$group" : {_id : {key:"$key", score:"$score"}}}, 
    // Clean up the output
    {"$project" : {_id:0, key:"$_id.key", score:"$_id.score"}}
])

Output:

{ "result" : [ { "key" : "SAGAR33", "score" : 37 } ], "ok" : 1 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

与多个字段和 mongodb 中的 where 条件不同 的相关文章

随机推荐