簡體   English   中英

如何將 mongodb 陣列中的值與另一個陣列匹配

[英]How to match values in mongodb array with another array

用戶文件

這是我的mongodb中的一個用戶文檔,還有很多其他的用戶文檔。 並且有很多這樣的興趣

myInterests['gaming','reading']

這個數組將來可以是動態的

我想編寫一個查詢,在其中可以獲取具有這 2 個興趣或至少 1 個興趣的用戶列表,我該如何為此編寫查詢?

router.get("/", auth, async function (req, res) {
  const { interests: myInterests } = req.user;
  const users = await User.find({
    interests: { $in: [myInterests] },
  }).select({ email: 1, interests: 1 });
  console.log(users);
});

我已經嘗試過這段代碼,但這段代碼讓我得到了那些只有這兩個興趣的用戶的列表。 我也想得到那些至少有這個數組元素之一的用戶。

myInterests已經是一個數組。 查詢應該是這樣的

interests: {
      $in: myInterests,
    }

代替

interests: {
      $in: [myInterests],
    }

否則,它會使用 2D 數組查找精確匹配。

工作場所 => https://mongoplayground.net/p/D2_JwvBUn3k

暫無
暫無

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

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