Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Join 如何在mongodb中加入查询?_Join_Mongodb_Schema - Fatal编程技术网

Join 如何在mongodb中加入查询?

Join 如何在mongodb中加入查询?,join,mongodb,schema,Join,Mongodb,Schema,我有这样的用户文档集合: User { id:"001" name:"John", age:30, friends:["userId1","userId2","userId3"....] } { "_id" : "userId", "name" : "John", "age" : 30, "friends" : [ { "_id" : "userId1", "name" : "Derek", "age" : 34 }

我有这样的用户文档集合:

User {
   id:"001"
   name:"John",
   age:30,
   friends:["userId1","userId2","userId3"....]
}
{
    "_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 }
    ]
}
一个用户有很多朋友,我有以下SQL查询:

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

我希望在MongoDB中有类似的功能。

MongoDB没有连接,但在您的情况下,您可以执行以下操作:

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

编辑:此答案仅适用于v3.2之前的MongoDb版本。

你不能在一个查询中做你想做的事情。您必须首先检索好友用户ID列表,然后将这些ID传递给第二个查询,以检索文档并按年龄对其进行排序

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

您可以使用playOrm在一个查询中执行您想要的操作(使用S-SQL可伸缩SQL)。

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} } )
var p=db.sample1.find().limit(2),
h=[];
对于(变量i=0;i
它对我很有用。

这是mongodb中用于连接查询的文档,这是3.2版的新功能


因此,这将很有帮助。

要使用聚合框架的$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" }
            }
        }
    ]
)
假设用户集合的内容如下所示:

{
    "_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
        }
    ]
}

你可以用它一次完成。下面是它的样子:

const joinQuery=require(“mongo连接查询”);
joinQuery(
mongoose.models.User,
{
查找:{},
填充:[“朋友”],
排序:{age:1},
},
(err,res)=>(err?console.log(“Error:,err”):console.log(“Success:,res.results))
);
结果将使您的用户按年龄排序,并嵌入所有friends对象

它是如何工作的?
幕后
mongojoinquery
将使用您的Mongoose模式来确定要加入的模型,并将创建一个将执行加入和查询的模型。

仅填充数组朋友

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

User {
   id:"001"
   name:"John",
   age:30,
   friends:["userId1","userId2","userId3"....]
}
{
    "_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 }
    ]
}

与此相同:

您可以在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();
最后,如果只想获取某个集合的某些字段,可以使用Propertie select示例:

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

您好,我不明白您的意思,我想获得指定用户的朋友,并按年龄对这些朋友进行排序。您好,我已经阅读了mongodb.org/display/DOCS/Querying,但我找不到解决方案。因此我在这里提问。如果朋友列表是对称的,这是正确的解决方案:如果a是B的朋友,那么B将是a的朋友。pingw33n在这里做的是说:给我所有拥有
userId
作为朋友的用户。所以这不是找到用户,而是找到他们的朋友。如果你的友谊关系不是对称的(如果它是跟随类型的关系,如Twitter,那么你必须采用dannie.t的方法,分两个阶段进行。或者为反向关系添加一个字段('friendedBy',say'),并以这种方式进行。这是“去规范化”:使用MongoDB 3.2,您可以使用聚合函数($lookup),这将留下joinNote,问题中发布的SQL也是两个查询(尽管使用一个组织更好的查询(如friends表)是可能的),我认为如果您将其转换为“适当的”任何了解数据库设计和规范化的人都会自动将数据库好友放在一个单独的表中。实际上,您最好在sql端使用一个关系实体,这样您就可以选择用户。*从用户在friends.friend\u id=users.id和friends.user\u id=?order by users.age。。。而不是两个有效用户表…我想问题不在于选择工具(我不认为这些家伙毕竟发明了魔杖).是的,但总是很高兴知道/有更多的选择…..我个人知道我很感激这样的答案。一个解释可能会有所帮助。也许你需要数据库引用-很好,我很困惑你如何对集合中的一个项目执行这样的操作(findOne等价物在哪里)?编辑:似乎$match可以做到这一点。我想知道这是否比2次查询更有效,因为
$match
不会停止搜索,而不像
findOne
。我想知道高于它的
$limit
是否会有所帮助。