簡體   English   中英

如何在 mongodb 中查詢文檔數組的元素

[英]How to query element of array of document in mongodb

我只是花了整個晚上試圖弄清楚這一點,我在 db 中有這樣的用戶:

[
    {
        "_id": "5fcff6ed224670346c8b60de",
        "name": "john",
        "password": "147",
        "data": [
            {
                "_id": "5fd000356d5df538d0338db4",
                "comment": "comment1",
                "date": "2020-12-08T22:37:41.740Z"
            },
            {
                "_id": "5fd0003e6d5df538d0338db6",
                "comment": "comment2",
                "date": "2020-12-08T22:37:50.271Z"
            },
            {
                "_id": "5fd000476d5df538d0338dba",
                "comment": "comment3",
                "date": "2020-12-08T22:37:59.128Z"
            }
        ],
        "__v": 6
    },
    {
        "_id": "5fcff6f5224670346c8b60df",
        "name": "Samantha",
        "password": "123",
        "data": [],
        "__v": 0
    },
]

當用戶“john”登錄時,他想檢索第 1 條評論,我該怎么做?

我想出了如何刪除它,但不知道如何找回它

router.delete("/:id", auth, async (req, res) => {
  let user = await User.findByIdAndUpdate(
    req.user._id,
    {
      $pull: {
        data: { _id: req.params.id },
      },
    },
    { new: true }
  );
  res.send(user.data);
});

我什至放棄了,試圖只檢索整個用戶,然后過濾數據,但它沒有用

router.get("/:id", auth, async (req, res) => {
  let user = await User.findById(req.user._id);
  let arr = user.data
  arr = arr.filter(e => e._id === req.params.id)
  res.send(arr)
});

您可以像這樣使用查詢和投影:

db.getCollection('users').find({
  "data": {
    $elemMatch: {
      comment: "comment1"
    }
  },
  "name": "john"
},
{
  "data.$": 1
})

使用$elemMatch ,您可以在嵌入文檔上指定多個條件。

然后,您將結果投影為僅返回具有以下條件的第一個元素
{comment: "comment1"}{name: "john"}

您將獲得只有一個索引的數據數組,這正是您所要求的。

暫無
暫無

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

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