查询MongoDB文档中的子图表,并且仅返回匹配的子图表
我在这里看: https://codelikethis.com/查询在这里: https://www.mongodb.com/community/forums/t/what-what------在mongodb/115315中使用sub-documents 尝试弄清楚如何仅查询父母文档中的子图表。
这是数据的示例:
{'testname':'process',
'jobId':"job1",
"vt_cond":"cond1",
"testData":[{
'chip':'c1',
'name':'block1'},
{
'chip':'c1',
'name':'block1'},
{
'chip':'c1',
'name':'block2'},
{
'chip':'c1',
'name':'block3'}]}
它包含“ TestData”字段中的子图表。我想做的是以下内容:
db.collection.find({'jobId':'job1', 'testData.name':'block3'})
让它返回以下内容:
{'testname':'process',
'jobId':"job1",
"vt_cond":"cond1",
"testData":[{'chip':'c1',
'name':'block3'}]}
i 了解 MongoDB文档指出它将查询并返回与子记录查询条件中条件相匹配的文档。确实如此。我得到了上面的整个示例文档。 无论如何,我是否可以使用与上述类似的条件进行类似的查询,并且只能返回带有所需子记录的父节点,而不是所有子图表?
Ive looked here: https://codelikethis.com/lessons/db/mongodb-array-queries and here: https://www.mongodb.com/community/forums/t/what-is-the-best-way-to-query-an-array-of-sub-documents-in-mongodb/115315 to try and figure out how to query only matching subdocuments from a parent document.
Here is an example of the data:
{'testname':'process',
'jobId':"job1",
"vt_cond":"cond1",
"testData":[{
'chip':'c1',
'name':'block1'},
{
'chip':'c1',
'name':'block1'},
{
'chip':'c1',
'name':'block2'},
{
'chip':'c1',
'name':'block3'}]}
It contains subdocuments within the "testData" field. What I want to do is something like the following:
db.collection.find({'jobId':'job1', 'testData.name':'block3'})
and have it return the following:
{'testname':'process',
'jobId':"job1",
"vt_cond":"cond1",
"testData":[{'chip':'c1',
'name':'block3'}]}
I understand that the mongodb documentation states it will query and return a document which matches the conditions in the subdocument query conditions. It does. I get the entire example document as above. Is there anyway where I can make a similar query with similar conditions as above, and only return the parent node with the desired subdocument, instead of ALL the subdocuments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项1:您可以在项目部分中使用$ Elemmatch如下:
说明:
仅找到匹配标准的数组sub-object符合标准的
关注:仅当您仅需要1倍时才能工作匹配数组的匹配元素,如果匹配条件中的一个元素要多于一个元素,则可以更好地使用选项2
。 a>
选项2:汇总/$ filter(当您在阵列中匹配的阵列中一个对象时,请覆盖以下情况)
解释:
态
Option 1: You can use $elemMatch in the project part as follow:
Explained:
Find the object and project only the array sub-object that match the criteria
Attention: This is only working if you need only 1x matching element from array , if there is more then one element in the array matching the criteria better use Option 2.
Playground
Option 2: aggregate/$filter ( cover the case when you have more then one objects in the array matching by the filter )
Explained:
Playground 2