簡體   English   中英

如何返回MongoDB文檔中數組所有元素的屬性?

[英]How to return property of all elements of array inside MongoDB document?

我想返回用戶文檔的trips數組中每個元素的title_id屬性。 我正在嘗試使用聚合管道,但這是我的第一次,而且文檔太多了。 似乎所有示例都顯示了如何查找單個數據。 我基本上想返回類似的東西


[
  {title: "one", _id: 123},
  {title: "two", _id: 456},
  {title: "three", _id: 789},
]

從我的文件看起來像:

在此處輸入圖像描述

提前感謝您的任何建議。

function ObjArray(array){
    let newArr = [];
    array.foreach(
    (obj) => {
        let newobj = {title: '', id:''}
        newobj.title = obj.title;
        newobj.id = obj.id;
        newArr.append(newobj);
    }
    );
    return newArr;
}

您可以使用find({})來獲得您的預期結果。 在查找查詢中,您需要使用投影階段。

這里演示

預期查詢

db.collection.find({},{_id:1,"trips.title":1,"trips._id":1});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM