Home > Back-end >  mongoose find in document object
mongoose find in document object

Time:05-25

Lets say I have a mongoose schema, something like:

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

where data field contains JSON Object. Something like:

{
   "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
      }
   ]
}

Is there any way I can get all documents, where data field object contains http://localhost:3000/login as url, without getting all the documents first and looping them through.

Object is going to be dynamic generated, and items will repeat themselves

CodePudding user response:

Sure you can do that. You can specify the object nesting in form of string in the query.

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

CodePudding user response:

Of course, there are several ways and in this case, one of the best ways is to use "aggregate"

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

return Response :

{
 "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"
   }
  ]
 }

If i find other or better methods, I'll definitely share.. I hope this solution helps you.

  • Related