本文介绍了与多个字段和mongodb中的where条件不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想写一个与mongodb
中的distinct
和where
等效的查询. sql查询是select DISTINCT key,score from GPC where note="test2" and notetwo = "meet2"
I want to write a query equivalent to distinct
and where
in mongodb
. the sql query is 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" }
查询的预期结果是
mongodb
中的等效查询是什么.我正在使用猫鼬执行查询.
What is the equivalent query in mongodb
. I am using mongoose to execute queries.
推荐答案
您需要使用查询以实现此目的.这是一个可以在shell中运行的示例(可以轻松转换为Mongoose):
You'll need to use the aggregate
queries for achieving this. Here's an example that will work in shell (which can be translated to Mongoose easily):
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"}}
])
输出:
{ "result" : [ { "key" : "SAGAR33", "score" : 37 } ], "ok" : 1 }
这篇关于与多个字段和mongodb中的where条件不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!