简体   繁体   English

2个集合中的mongodb查询

[英]mongodb query in 2 collections

I have define 2 reconds in 2 collections separately in one mongo db like this 我像这样在一个mongo db中分别在2个集合中定义了2个reconds

order:

{

    "_id" : ObjectId("53142f58c781abdd1d836fcd"),
    "number" : "order1",
    "user" : ObjectId("53159bd7d941aba0621073e3")
}

user

{

    "_id" : ObjectId("53159bd7d941aba0621073e3"),
    "name" : "user1",
    "gender" : "male"

}

when I use this command in console, it can not execute db.orders.find({user: db.user['_id']}) or db.orders.find({user: user['_id']}), 当我在控制台中使用此命令时,它无法执行db.orders.find({user:db.user ['_ id']})db.orders.find({user:user ['_ id']}),

is there anything wrong? 有什么问题吗? Thanks! 谢谢!

Another way is to: 另一种方法是:

> var user = db.users.findOne({name: 'user1'}); 
> db.orders.find({user: user._id});

This way can be a bit more flexible especially if you want to return orders for multiple users etc. 这种方式可以稍微灵活一些,特别是如果您要退回多个用户的订单等时。

Taking your comment: 发表您的评论:

Thanks, but actually, I want to search all the orders of all users, not only one user. 谢谢,但是实际上,我想搜索所有用户的所有订单,而不仅仅是一个用户。 So what would I do? 那我该怎么办? Thanks 谢谢

db.users.find().forEach(function(doc){
    printJson(db.orders.find({user: doc._id}));
});

I think you want: 我想你要:

db.order.find({'user':db.users.findOne({'name':'user1'})._id})

All you need to do is to make a query and check the output before inserting it into the query. 您需要做的就是查询并在将输出插入查询之前检查输出。

ie check that: 即检查:

db.users.findOne({'name':'user1'})._id

has the output: 具有输出:

ObjectId("53159bd7d941aba0621073e3")

If you want to run larger queries, you're going to have to change your structure. 如果要运行较大的查询,则必须更改结构。 Remember that Mongodb doesn't do joins so you'll need to do create a user document that looks like this: 请记住,Mongodb不执行联接,因此您需要创建一个如下所示的用户文档:

user
{
 "name":"user1",
 "gender":"male",
 "orders":[
    {
     'number':'order1'
    }
 ]
}

You can then update this using: 然后,您可以使用以下方法更新此内容:

 db.user.update({'_id':ObjectId('blah')}, {'orders':{$push:{'number':'order2'}})

This will then start you with order tracking. 然后,您将开始进行订单跟踪。

Mongo will be able to find using the following: Mongo将能够使用以下内容进行查找:

 db.user.find({'orders.numbers':'order2'})

returning the full user record 返回完整的用户记录

Maybe you can help this solution: 也许您可以帮助解决方案:

use orders
db.getCollection('order').find({},{'_id':1})
db.getCollection('user').find({},{'_id':1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM