猫鼬在文档对象中查找

mongoose find in document object

假设我有一个猫鼬模式,例如:

mongoose.Schema({
website_id:mongoose.SchemaTypes.ObjectId,
data:Object
})

其中 data 字段包含 JSON 对象。类似于:

{
   "actions":[
      {
         "action":"pageChange",
         "url":"http://localhost:3000/login",
         "dom":"",
         "timestamp":1653341614846
      },
      {
         "action":"pageChange",
         "url":"http://localhost:3000/signup",
         "dom":"",
         "timestamp":1653341626442
      },
      {
         "action":"pageChange",
         "url":"http://localhost:3000/view",
         "dom":"",
         "timestamp":1653341626442
      },
      {
         "action":"pageChange",
         "url":"http://localhost:3000/login",
         "dom":"",
         "timestamp":1653341626442
      }
   ]
}

有什么方法可以获取所有文档,其中 数据字段对象 包含 http://localhost:3000/login 作为url,没有先获取所有文档并循环遍历它们。

对象将被动态生成,项目将自己重复

当然可以。您可以在查询中以字符串形式指定对象嵌套。

await MyModel.find({ 'data.objectKey.items.item': 'text I want to find' }).exec();

当然,有几种方法,在这种情况下,最好的方法之一是使用“聚合”

 db.collection.aggregate([
   {$unwind: "$actions"},
   { $match: {"actions.url": "http://localhost:3000/login"}},
   {$group: {
     _id: "$_id",
     actions: {$push: "$actions"}
     }
   }
 ])

return 响应:

{
 "actions": [
   {
    "action": "pageChange",
    "dom": "",
    "timestamp": 1.653341614846e+12,
    "url": "http://localhost:3000/login"
    },
    {
    "action": "pageChange",
    "dom": "",
    "timestamp": 1.653341626442e+12,
    "url": "http://localhost:3000/login"
   }
  ]
 }

如果我找到其他或更好的方法,我一定会分享.. 我希望这个解决方案对你有所帮助。