简体   繁体   English

使用 Pymongo 查找数组内的文档

[英]Find document that is inside an array using Pymongo

I am really new on Mongo, I have been trying to extract a document that is inside an array, using pymongo, without any result.我对 Mongo 真的很陌生,我一直在尝试使用 pymongo 提取数组内的文档,但没有任何结果。 The next image shows the structure of the mongos database.下图显示了 mongos 数据库的结构。

在此处输入图片说明

I just want to extract for example the first or the second document that belongs to the "data" array.我只想提取例如属于“数据”数组的第一个或第二个文档。 I have tried with the next codes:我已经尝试过以下代码:

data = condition.find_one({},{'data.ref':2})
data = condition.find({ 'data': {'$eq': '1'} })
data = condition.find({'data.ref':1})
data = condition.find({'_id':1},{'data.ref':1})
data = condition.find({'data.ref':1},{'trq.min':50})
data = condition.find({ "data" : { "$elemMatch" : { "ref" : 1} }})

I would appreciate any reference to consult or any help in order to extract a single document from this array.我将不胜感激任何参考或任何帮助,以便从此数组中提取单个文档。

You can use the $elemMatch(projection) to project that desired array value.您可以使用$elemMatch(projection)投影所需的数组值。

Please note that I just convert the cursor to a list for easy handling.请注意,我只是将光标转换为列表以便于处理。

Based on the following document:基于以下文件:

{'_id': 1,
 'data': [{'1': {'trq': {'max': 100, 'min': 50}}, 'ref': 1},
          {'2': {'trq': {'max': 50, 'min': 50}}, 'ref': 2}],
 'max': 100,
 'min': 30}

The following query will return the first ref and suppress the id:以下查询将返回第一个 ref 并取消 id:

mlist1 = list(coll.find({}, {
    '_id': 0,
    'data': {'$elemMatch': {'ref': {'$eq': 1}}}
}))

Results:结果:

{'data': [{'1': {'trq': {'max': 100, 'min': 50}}, 'ref': 1}]}

For the second one:对于第二个:

mlist1 = list(coll.find({}, {
    '_id': 0,
    'data': {'$elemMatch': {'ref': {'$eq': 2}}}
}))

Results:结果:

{'data': [{'2': {'trq': {'max': 50, 'min': 50}}, 'ref': 2}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM