简体   繁体   中英

MongoDB and Mongoose: How to retrieve nested Object

I have the following documents in my mongodb collection:

{ 
    "current" : 
    { 
        "aksd" : "5555", 
        "BullevardBoh" : "123" 
    }, 

    "history" : 
    { "1" : { 
            "deleted" : false, 
            "added" : false, 
            "date" : "21-08-2014" 
            }
    }, 

    { "2" : { 
            "deleted" : false, 
            "added" : false, 
            "date" : "01-01-2013" 
            }
    }, 

    "_id" : ObjectId("53f74dad2cbfdc136a07bf16"), 
    "__v" : 0 
}

I have multiple of these documents. Now I want to achieve two things with my Mongoose/Express API.

  1. Query for all nested "current" in each document and retrieve them as JSON objects like such: {"aksd":"5555","BullevardBoh":"123"},{..},{..} .

  2. Retrieve all history revisions (1,2...) where "date" is smaller than a given date.

As you can clearly see this is a kind of versioning I am trying to implement. I would also be interested if this kind of data structure will get indexed by MongoDB and if there is possibly a better way. (eg with arrays inside objects?)

This isn't working in MongoDB:

db.ips.findOne({current.aksd: {$exists:true}});

I think the quotes around the field are missing here:

db.ips.findOne({current.aksd: {$exists:true}});

This should work instead:

db.ips.findOne({"current.aksd": {$exists:true}});

While Ritesh's reply was a step in the right direction, I rather wanted to fetch the current object literal and its members inside the document not the whole document.

1.) Query for all nested "current" in each document

db.ips.find({"current":{$exists:true}}, {"current":1});

This is giving back all nested documents where the aksd literal is present:

{ "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "_id" : ObjectId("53f74dad2cb3dc136a07bf16") }
...

2.) Retrieving history revisions where date is smaller then a given date:

db.ips.find({"history.date": {$lt: "01-01-2014"}},{history:{$elemMatch:{date: {$lt:"01-01-2014"}}}});

Giving back the wanted nested date literal(s):

{ "historie" : [  {  "date" : "01-01-2013",  "added" : false,  "deleted" : false } ], "_id" : ObjectId("53faf20f399a954b2b7736b6") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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