我正在尝试使用tornado和python从MongoDB集合中检索值。
我为搜索提供的值在列表中,我希望列出整个集合,但给定值以外的值不得显示在列表变量中。
表中我的数据:
{
"_id" : ObjectId("564b313b3f32df05fc905570"),
"RequiredDate" : "17-11-2015",
"RequestedDate" : "17-11-2015",
"Pid" : [
"564b22373f32df05fc905564",
"5630baac3f32df134c18b682"
],
"email" : "abishek@gmail.com",
"UName" : "abishek",
"Uid" : "564b21003f32df05fc905563",
"phone" : "9988776655",
"PName" : [
"balu",
"prakash"
],
"Registration" : [
"TN 45 AG 5688",
"TN 45 AS 5655"
],
"Rid" : "564b313b3f32df05fc905570"
}
我的查询:
db.collection.find({"Rid" : "564b313b3f32df05fc905570"},{"Pid": {$elemMatch:{"Pid":"5630baac3f32df134c18b682","Registration": "TN 45 AS 5655"}}},{"_id": false}).pretty()
所需的输出是:
{
"_id" : ObjectId("564b313b3f32df05fc905570"),
"RequiredDate" : "17-11-2015",
"RequestedDate" : "17-11-2015",
"Pid" : "5630baac3f32df134c18b682",
"email" : "abishek@gmail.com",
"UName" : "abishek",
"Uid" : "564b21003f32df05fc905563",
"phone" : "9988776655",
"PName" : [
"balu",
"prakash"
],
"Registration" : "TN 45 AS 5655",
"Rid" : "564b313b3f32df05fc905570"
}
$elemMatch
是获取输出的正确方法吗?或者是否有其他方法可以实现所需的输出。
说明:
在建议的答案中,列表中有一个 JSON 对象,这里有一个特定的值,其中只有 Pid 知道从另一个表接收的注册值与该特定记录中的注册值相匹配,并且然后显示为单个记录,而不显示其他 Pid 和注册。
我在输出中仅获得 _id
,而不是整个修改记录。
最佳答案
下面的查询几乎给出了您想要的内容,但是,它不会将 Pid
和 Registration
存储在数组中。如果需要,您可以使用 $group
语句结合 $push
创建此数组,但是,您必须在 group 语句中包含所有字段。
db.collection.aggregate([{$match:{"Rid" : "564b313b3f32df05fc905570"}},
{$unwind:"$Pid"},
{$unwind:"$Registration"},
{$match:{"Pid" : "5630baac3f32df134c18b682"}},
{$match:{"Registration" : "TN 45 AS 5655"}}])
您可以使用$project
过滤数据:
db.data.aggregate([{$match:{"Rid" : "564b313b3f32df05fc905570"}},
{$unwind:"$Pid"},
{$unwind:"$Registration"},
{$match:{"Pid" : "5630baac3f32df134c18b682"}},
{$match:{"Registration" : "TN 45 AS 5655"}},
{$project:{"_id":0,"Rid":1,"Pid":1,"Registration":1}}])
如果此查询返回重复项(如评论中所述),您可以添加另一个 $group
语句来删除重复项:
db.data.aggregate([{$match:{"Pid" : "5630baac3f32df134c18b682"}},
{$unwind:"$Pid"},
{$unwind:"$Registration"},
{$match:{"Pid" : "5630baac3f32df134c18b682"}},
{$match:{"Registration" : "TN 45 AS 5655"}},
{$project:{"_id":0,"Rid":1,"Pid":1,"Registration":1}},
{$group:{"_id":{"Rid":"$Rid","Pid":"$Pid","Registration":"$Registration"}}},
{$project: {"_id":0,"Rid":"$_id.Rid","Pid":"$_id.Pid","Registration":"$_id.Registration"}},
])
关于python - 使用 $elemMatch 进行 MongoDB 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33777270/