【问题标题】:querying nested object arrays from mongodb / nodejs从 mongodb / nodejs 查询嵌套对象数组
【发布时间】:2019-02-28 22:24:27
【问题描述】:

我试图弄清楚如何查询Components 对象内的嵌套对象。数据是从解析的 json 文件中插入的。

查询

var query = {}
cursor = db.collection("workflows").find(query).toArray(function(err, result) {
if (err) throw err;

console.log(result);
db.close();
    });

当我运行上面的查询时会返回此数据:

此时我只是试图让它以某种方式过滤。我尝试了Name:'Test WF' 和其他变体,但仍然无法获得过滤响应。

[ { _id: 5c77040838f9d322b89bbd82,
texto:
 { _id: 12,
   LocalCachePath: 'Z:\\Test\\Cache',
   SharedCachePath: [],
   Name: 'Test WF',
   Desc: 'I\'m testing',
   Components: [Array] } },
{ _id: 5c7704164413692978a9dd1a,
texto:
 { _id: 'Workflow-2019.02.22-23.21.15-MKRU',
   LocalCachePath: 'Z:\\MAITest\\Cache',
   SharedCachePath: [],
   Name: 'Test WF',
   Desc: 'I\'m testing',
   Components: [Array] } },
 { _id: 5c77046335b012379c99951b,
texto:
 { _id: '154',
   LocalCachePath: 'Z:\\Test\\Cache',
   SharedCachePath: [],
   Name: 'Test WF',
   Desc: 'I\'m testing',
   Components: [Array] } },
 { _id: 5c7704787bde6f36543d1016,
texto:
 { _id: 'Workflow-2019.02.22-23.21.15-MKRU',
   LocalCachePath: 'Z:\\Test\\Cache',
   SharedCachePath: [],
   Name: 'Test WF',
   Desc: 'I\'m testing',
   Components: [Array] } } ]

任何见解都会对我一次步履蹒跚的这一步有所帮助。

这是另一个给我结果的查询,但我想我的问题是将我的结果解析为变量。

var query = {'texto.Components.0.Name' : {$gt: ''}}
// var query = {'testo.Name' : {$gt: ''} }
 cursor = db.collection("workflows").find(query).toArray(function(err, result) {
    if (err) throw err;

【问题讨论】:

  • Desc! “以某种方式过滤”是什么意思?你能说得更具体点吗?
  • 您到底想要返回什么?
  • 我真的很想进入组件级别并访问其子节点中的数据。我希望能够为文件中的每个节点提取字段名称和值。

标签: node.js json mongodb nested


【解决方案1】:

使用点表示法(例如 texto.Name)从嵌套对象中查询和检索字段,例如:

var query = {'texto.Name': 'Test WF'}

【讨论】:

  • 酷。它立即起作用。谢谢:)
【解决方案2】:

简单

db.getCollection('TestQueries').find({'texto.Name': 'Test WF'})

用于不区分大小写的正则表达式。

db.getCollection('TestQueries').find({"texto.Name":{
                                 '$regex' : '^test wa$', '$options' : 'i'
                                 }})

使用排序规则

db.fruit.createIndex( {"texto.Name": 1},{ collation: {
                     locale: 'en', strength: 2 
                     } } )

db.getCollection('TestQueries').find( 
            { "texto.Name": "test wa" } ).collation( { locale: 'en', strength: 2 } 
            )

【讨论】:

  • 感谢您的输入,这是我所拥有的,但我得到的是 db.getCollection is not a function var query = {'texto.Name': 'Test WF'} cursor = db. getCollection('workflows').find({query})(function(err, result) { if (err) throw err; console.log(result); db.close(); });
  • 我只是在 Robo 3T 上运行它。这就是我使用 getCollection 的原因。我想你可以试试 db.collection db.collection()
  • 我有相同的数据流,但它提供的是所有数据而不是匹配的数据,下面是我的代码。 { "$match": { "$or": [ { "product_categories.product_list.name": { "$regex": ".*samo.*", "$options": "i" } } ] } }
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 2016-09-05
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2018-11-01
  • 2019-05-17
  • 2018-09-10
相关资源
最近更新 更多