使用$ elemMatch进行Mongo数据库查询

时间:2015-11-18 10:15:13

标签: python mongodb

我正在尝试使用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知道从另一个表接收的Registration值与此特定记录中的Registration值匹配,然后显示为单个记录而不显示其他Pid和注册。 我只输出_id输出,而不是整个修改过的记录。

1 个答案:

答案 0 :(得分:1)

以下查询几乎可以提供您所追求的内容,但是,它不会将PidRegistration存储在数组中。如果需要,您可以使用$group语句结合$push创建此数组,但是,您必须在组语句中包含所有字段。

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"}},

])