简体   繁体   中英

mongodb query in 2 collections

I have define 2 reconds in 2 collections separately in one mongo db like this

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']}),

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:

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:

 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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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