如何访问对象的嵌套数组

我在数据库中有一个名为 bills 馆藏

集合中的每个文档都是在国会中通过的账单。

在每个文档中,都有一个名为 votingRecord 的数组,该数组由作为每个国会议员投票记录的对象组成。

我需要能够在votingRecord array 内排序和查找特定的键/值,而我无法弄清楚。

我尝试了此处列出的示例,但是我的问题是,集合中的每个文档都有由代表组成的嵌套对象数组(“ votingRecord”)。

我需要在查询中设置一个初始过滤器,以便可以在特定的BillingRecord中搜索特定的帐单。

{
    "_id" : ObjectId("5dc209b7af26e560a3204bcc"),"bill_id" : "hr676-116","title" : "To reiterate the support of the Congress of the United States for the North Atlantic Treaty Organization,and for other purposes.","sponsorState" : "CA","sponsorParty" : "D","summary" : "NATO Support act  This bill prohibits the appropriation or use of funds to withdraw the United States from the North Atlantic Treaty Organization.","primarySubject" : "NATO Support act  This bill prohibits the appropriation or use of funds to withdraw the United States from the North Atlantic Treaty Organization.","introducedDate" : "2019-01-17","latestMaction" : "Received in the Senate.","votingRecord" : [ 
        {
            "person" : 400440,"state" : "AK","district" : 0,"vote" : "Yea","name" : "Rep. Don Young [R]","party" : "Republican"
        },//( five hundred or so of these objects(all reps + senators),ending with)

],"latestMactionDate" : "2019-01-23","__v" : 0
}

我的MongoDB shell没有响应我所做的任何查询。

db.bills.find({"introducedDate": 2019-01-03},{votingRecord: {$elemMatch: {state:"FL"}}})

上面的查询感觉像是最接近的查询,因为我是用“ introducedDate”指定的,但到目前为止还算不上运气。

wohongming 回答:如何访问对象的嵌套数组

如果您要从votingRecord数组中过滤掉不相关的条目,则可以使用以下查询:

db.bills.find({"introducedDate": "2019-01-17","votingRecord.state": "FL"},{
   "votingRecord.$": 1,//using $ will only project matched objects   
   //..other fileds that you want to project

});

已提供,您希望该帐单在2019年1月17日生效,投票记录来自“ FL”状态。

但是 ,可以说

您想要的帐单日期为2019年1月3日,投票记录来自“ FL”州和地区“ 0”。

将上述查询与district的附加条件一起使用将无济于事,

由于无法得到,我们希望在vottingRecord的相同对象中,状态为“ FL”,为0 / strong>,它的作用类似于 OR 条件

要将其用作AND,您需要使用$ elemMatch运算符

像这样

db.bills.find({"introducedDate": "2019-01-03","votingRecord": {$elemMatch: {state:"FL",district: 0}}},//using $ will only project matched objects   
   //..other fileds that you want to project

});
本文链接:https://www.f2er.com/3140311.html

大家都在问