简体   繁体   中英

How do I formulate a query to return the elements of an inner array in an Object?

In my browser Console, my db.Collection.find("CJiuk6jjFEBLDQrQc").fetch() returns a cursor with an object , and an array called viewStatisticsArray .

Find below a demonstration of the returned cursor:

_id: "CJiuk6jjFEBLDQrQc"
DatePosted: Wed Feb 15 2017 15:10:50 GMT+0300 (EAT)
createdBy: "Mr. Walkings"
viewStatisticsArray: Array[2]

When the viewStatisticsArray is clicked it shows two Objects with two elements: nrOfViews and statsDate .

It is the value of these elements that are of interest to me.

I have tried

db.Collection.find({"CJiuk6jjFEBLDQrQc"}).fetch().map(function(u) {
   console.log("Array: " + u.viewStatisticsArray); // Array: [object Object],[object Object]
   console.log("Number of Viewers: " + .viewStatisticsArray.nrOfViews); // Number of Viewers: undefined
   console.log("Stats Date: " + u.viewStatisticsArray.statsDate); // Stats Date: undefined      

return u.viewStatisticsArray
});

Oddly enough the return u.viewStatisticsArray returns the Array[2] .

How do I formulate a query to return a cursor with the inner elements of the viewStatisticsArray Array?

Looking forward to your help.

The reason you are having trouble is because you are trying to access each index of the viewStatisticsArray as if it was an object.

u.viewStatisticsArray.statsDate

However, viewStatisticsArray is an array that contains 2 objects. So if you want to get those values, you must iterate over the array like this.

db.Collection.find({"CJiuk6jjFEBLDQrQc"}).fetch().map(function(u) {
  console.log("Array: " + u.viewStatisticsArray); // Array: [object Object],[object Object]

  u.viewStatisticsArray.forEach(function(e, i) {
    console.log("Number of Viewers - index " + i ": " + e.nrOfViews);
    console.log("Stats Date - index " + i ": " + e.statsDate);
  });
});

Because your document field is an array, there is no way to iterate over the elements in the array with a mongodb cursor. A mongodb cursor only iterates over documents in a collection. Just use regular javascript to iterate over a field in a document that is an array (as I demonstrated above).

Lastly, it sounds like even though the viewStatisticsArray is an array of objects, based on your question, it sounds like you might only care about the last index in the array (which is probably the latest date view counts were calculated). In that case you can do something like this to get that single object.

var latestStats = db.Collection.find({"CJiuk6jjFEBLDQrQc"}).fetch().pop().viewStatisticsArray.pop();

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