簡體   English   中英

使用mongoose查詢mongoDB中的子文檔

[英]Querying sub documents in mongoDB using mongoose

我是初學者全棧 web 開發人員。 我正在嘗試制作一個電影評級網站。 所以我有一個使用 mongoose 的用戶模式和模式中的評級子文檔。 架構示例:

const ratingSchema = new mongoose.Schema({
    name: String,
    url: String,
    rating: {
        type: Number,
        min: 0,
        max: 10
    },
    comment: String
})

const userSchema = new mongoose.Schema({
    email: String,
    username: String,
    password: String,
    ratings: [ratingSchema]
})

正在使用的模式示例如下:

const newuser = new User({
email: 'test1@a.com',
username: 'maintest',
password: 'aaaa',
ratings: [{
name: 'Avengers'
url: 'www.avengers.com',
rating: 5,
comment: 'Good Movie'
}]

})

給定上面的例子:我有一個頁面顯示每部電影的所有用戶評分,我還有一個搜索欄,我希望能夠搜索電影名稱並查看電影評分彈出窗口。 基本上我的問題是我如何查詢數據庫以獲取每個用戶的所有評分並從查詢中獲取每個電影名稱。 例如:我查詢整個數據庫和每個用戶..因為每個用戶都可以評價同一部電影並給它相同的名稱..並獲取評價電影“復仇者聯盟”的用戶的數據庫。 如果您需要有關此問題的更多信息,請隨時問我.. 謝謝

您可以完成所需的一種方法是:

db.getCollection("movie-ratings").aggregate([
  { $unwind: "$ratings" },
])

這將使您的所有文檔變平。 樣品 output:

{ "_id" : ObjectId("5eb059141d704dbea32156a9"), "email" : "test1@a.com", "username" : "maintest", "password" : "aaaa", "ratings" : { "name" : "Avengers", "url" : "www.avengers.com", "rating" : 5, "comment" : "Good Movie" } }
{ "_id" : ObjectId("5eb059141d704dbea32156a9"), "email" : "test1@a.com", "username" : "maintest", "password" : "aaaa", "ratings" : { "name" : "Hulk", "url" : "www.avengers.com", "rating" : 2, "comment" : "Good Movie" } }

此外,因為您在聚合中,所以您可以對其應用許多不同的聚合運算符。 例如,您可以應用匹配運算符來按特定標題進行過濾:

db.getCollection("movie-ratings").aggregate([
  { $unwind: "$ratings" },
  { $match: { 'ratings.name': 'Avengers' } }
])

您可以在此處閱讀有關不同運算符的更多信息:

https://docs.mongodb.com/manual/reference/operator/aggregation-pipeline/

更新:使用 mongoose 你可以做這樣的事情。 假設你有一個名為 Ratings 的 mongoose model,那么你可以這樣做:

const aggregate = Ratings.aggregate([
  { $unwind: "$ratings" },
  { $match: { 'ratings.name': 'Avengers' } }
]);

您可以在此處找到有關使用 mongoose 的聚合的更多信息:

https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

我希望這可以幫助你。

根據此參考,未對其進行測試,但您可以使用 mongoose 嘗試類似的操作:

User.find().elemMatch('ratings', { name: 'Avengers'})

暫無
暫無

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

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