簡體   English   中英

如何在mongodb中加入查詢?

[英]How to join query in mongodb?

我有這樣的用戶文檔集合:

User {
   id:"001"
   name:"John",
   age:30,
   friends:["userId1","userId2","userId3"....]
}

一個用戶有很多朋友,我在SQL中有以下查詢:

select * from user where in (select friends from user where id=?) order by age

我想在 MongoDB 中有類似的東西。

要使用聚合框架的 $lookup 功能通過一個查詢獲得所有內容,請嘗試以下操作:

db.User.aggregate(
    [
        // First step is to extract the "friends" field to work with the values
        {
            $unwind: "$friends"
        },
        // Lookup all the linked friends from the User collection
        {
            $lookup:
            {
                from: "User",
                localField: "friends",
                foreignField: "_id",
                as: "friendsData"
            }
        },
        // Sort the results by age
        {
            $sort: { 'friendsData.age': 1 }
        },
        // Get the results into a single array
        {
            $unwind: "$friendsData"
        },
        // Group the friends by user id
        {
            $group:
            {
                _id: "$_id",
                friends: { $push: "$friends" },
                friendsData: { $push: "$friendsData" }
            }
        }
    ]
)

假設您的 User 集合的內容如下:

{
    "_id" : ObjectId("573b09e6322304d5e7c6256e"),
    "name" : "John",
    "age" : 30,
    "friends" : [
        "userId1",
        "userId2",
        "userId3"
    ]
}
{ "_id" : "userId1", "name" : "Derek", "age" : 34 }
{ "_id" : "userId2", "name" : "Homer", "age" : 44 }
{ "_id" : "userId3", "name" : "Bobby", "age" : 12 }

查詢的結果將是:

{
    "_id" : ObjectId("573b09e6322304d5e7c6256e"),
    "friends" : [
        "userId3",
        "userId1",
        "userId2"
    ],
    "friendsData" : [
        {
            "_id" : "userId3",
            "name" : "Bobby",
            "age" : 12
        },
        {
            "_id" : "userId1",
            "name" : "Derek",
            "age" : 34
        },
        {
            "_id" : "userId2",
            "name" : "Homer",
            "age" : 44
        }
    ]
}

編輯:此答案僅適用於 v3.2 之前的 MongoDb 版本。

您不能只在一個查詢中做您想做的事。 您必須首先檢索好友用戶 ID 列表,然后將這些 ID 傳遞給第二個查詢以檢索文檔並按年齡對它們進行排序。

var user = db.user.findOne({"id" : "001"}, {"friends": 1})
db.user.find( {"id" : {$in : user.friends }}).sort("age" : 1);

https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/

這是 mongodb 中連接查詢的文檔,這是 3.2 版的新功能。

所以這會很有幫助。

MongoDB 沒有聯接,但在您的情況下,您可以執行以下操作:

db.coll.find({friends: userId}).sort({age: -1})

您可以在 Moongoose JS .populate(){ populate : { path : 'field' } } 示例:

型號:

 mongoose.model('users', new Schema({
        name:String,
        status: true,
        friends: [{type: Schema.Types.ObjectId, ref:'users'}], 
        posts: [{type: Schema.Types.ObjectId, ref:'posts'}], 

    }));
 mongoose.model('posts', new Schema({
            description: String,
            comments: [{type: Schema.Types.ObjectId, ref:'comments'}], 

        }));
 mongoose.model('comments', new Schema({
            comment:String,
            status: true

        }));

如果您想查看朋友的帖子,可以使用此功能。

Users.find().                    //Collection 1
        populate({path:'friends',   //Collection 2
        populate:{path:'posts'   //Collection 3
        }})
    .exec();

如果您想查看朋友的帖子並帶上所有評論,您可以使用它,如果找不到並且查詢錯誤,您也可以識別集合。

 Users.find().                                    //Collection 1
        populate({path:'friends',                 //Collection 2
        populate:{path:'posts',                   //Collection 3
        populate:{path:'commets, model:Collection'//Collection 4 and more
        }}})
    .exec();

最后,如果您只想獲取某個集合的某些字段,則可以使用屬性選擇示例:

Users.find().                                    
        populate({path:'friends', select:'name status friends'                  
        populate:{path:'comments'               
        }})
    .exec();

一種在 mongoDB 中加入查詢,在一個集合中詢問匹配的 id,將 id 放入列表 (idlist) 中,並使用 $in 在其他(或相同)集合上查找使用:idlist

u = db.friends.find({"friends": ? }).toArray()
idlist= []
u.forEach(function(myDoc) { idlist.push(myDoc.id ); } )
db.friends.find({"id": {$in : idlist} } )

只填充數組朋友。

User.findOne({ _id: "userId"})
.populate('friends')
.exec((err, user) => {
    //do something
});

結果是一樣的:

{
    "_id" : "userId",
    "name" : "John",
    "age" : 30,
    "friends" : [
        { "_id" : "userId1", "name" : "Derek", "age" : 34 }
        { "_id" : "userId2", "name" : "Homer", "age" : 44 }
        { "_id" : "userId3", "name" : "Bobby", "age" : 12 }
    ]
}

同樣的: 貓鼬 - 在 ObjectId 數組上使用 Populate

您可以使用 playOrm 在一個查詢中執行您想要的操作(使用 S-SQL 可擴展 SQL)。

var p = db.sample1.find().limit(2) , 
    h = [];
for (var i = 0; i < p.length(); i++) 
{
  h.push(p[i]['name']);
}
db.sample2.find( { 'doc_name': { $in : h } } ); 

它對我有用。

您可以使用mongo-join-query一次性完成。 這是它的樣子:

const joinQuery = require("mongo-join-query");

joinQuery(
    mongoose.models.User,
    {
        find: {},
        populate: ["friends"],
        sort: { age: 1 },
    },
    (err, res) => (err ? console.log("Error:", err) : console.log("Success:", res.results))
);

結果將使您的用戶按年齡排序並嵌入所有朋友對象。

它是如何工作的?

在幕后mongo-join-query將使用您的 Mongoose 模式來確定要加入的模型,並將創建一個聚合管道來執行連接和查詢。

暫無
暫無

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

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