I need to select users for corresponding data from query.
I have this collection in my DB (two or more rows are output of my query as well)
> db.Friends.find()
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "3MTmHcJNEzaaS8hrd","_id" : "aiRD.." }
{ "userId" : "k3XCWdN5M2pbzBiFD", "followeeId" : "SoTozuZ4nWooRBeFz","_id" : "QingX.." }
When it would be just one result as findOne(...) the second query would looks like this:
users.findOne({ _id: firstQueryResult.followeeId })
But now the problem is... how can i select the users from users collection when i dont have only one followeeId but more of them?
Please someone show me an example of code.
My research:
Is this a good solution?
friendsData.forEach(function(relationShip) {
followeeIds.push(relationShip.followeeId);
});
console.log(followeeIds);
Ok i finalllly figure out the problem.For next readers:
Check if autopublish is enabled or disabled.
If is disabled you need to publish the collection from the DB
Meteor.publish("userData", function () {
return Meteor.users.find({},
{fields: {'username': 1}});
});
PS: i want to publish only username field and thats all!
You need to subscribe the data as well!
Meteor.subscribe("userData");
Now you can access other users data this way:
users= Meteor.users.findOne({username: "Nolifer"});
To my original problem ... i will probably use this function for iterate over more then one row result(its more a SQL term but i am not sure what term use in mongoDb maybe a document? whatever):
users.forEach(function(user) {
console.log(user);
});
Thats it!
P.S.: I think there is nothing wrong on this but what i know right? :) So if someone know a better way please leave a comment. If not give me know if it was useful for you :)
According to the mongo manual, use the $in operand: http://docs.mongodb.org/manual/reference/operator/in/#op._S_in
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )
Related
I have a simple question and I don't know how to formulate it clearly because my english is bad I will explain with an example:
the MongoDB object is like this :
{_id:ObjectId("606445724bd1552e94f60691"),email:"exemple#gmail.com",password:"password123"}
I want to add age for example the object will be :
{_id:ObjectId("606445724bd1552e94f60691"),email:"exemple#gmail.com",password:"password123",age:30}
just like this please help
Simply
db.collection.updateOne(
{ _id: ObjectId("606445724bd1552e94f60691") },
{ $set: { age: 30 } }
)
Hopefully you don't store passwords as clear text in your database!
I wonder if there's anything similar to mysql IN? Like this "where id in (1,3,5)"?
I have this in my group by condition and i want to do filter only certain ids and those ids are like the above case where using gte/lt once will be able to do the job.
Maybe not just for group by but find. Any help will be great. Thanks.
{"time" : {"$gte" : "2015-12-16", "$lt" : "2015-12-16"}}
You mean, like:
{ field: { $in: [1,3,5] } }
No. There's nothing like that in mongodb. Trust me. Nothing like that.
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.
i.e. 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})
I have a query as below.
Post.native(function(err, collection) {
collection.find({
$or: [ { id :id }, { parentid : id} ]
}, function(err, result) {
if (err)
console.log({error: err});
console.log(result);
});
});
But this returns zero results , even though i have one result satisfying {id : id} and two results satisfying {parentid : id}. I need three results to be printed.
Please correct me if my query is wrong. Any help would be appreciated.
Please help. Thanks a lot
Here are some of the most common things I would do to debug this problem.
If you use the native driver and the fields you are querying are MongoIds, you need to ensure that ids are instances of ObjectId, i.e.
id = new mongo.ObjectID(id)
Also, mongodb natively stores its id as _id. Did you specifically create an id field?
I'm wondering the best way to query mongo db for many objects, where each one has an array of _id's that are attached to it. I want to grab the referenced objects as well. The objects' schemas looks like this:
var headlineSchema = new Schema({
title : String,
source : String,
edits : Array // list of edits, stored as an array of _id's
...
});
...and the one that's referenced, if needed:
var messageSchema = new Schema({
message : String,
user : String,
headlineID : ObjectId // also contains a ref. back to headline it's incl. in
...
});
One part of the problem (well, depending if I want to keep going this route) is that pushing the message id's is not working (edits remains an empty array [] afterwards) :
db.headline.update({_id : headlineid}, {$push: {edits : messageid} }, true);
When I do my query, I need to grab about 30 'headlines' at a time, and each one could contain references to up to 20 or 30 'messages'. My question is, what is the best way to fetch all of these things? I know mongo isn't a relational db, so what I'm intending is to first grab the headlines that I need, and then loop through all 30 of them to grab any attached messages.
db.headline.find({'date': {$gte: start, $lt: end} }, function (err, docs) {
if(err) { console.log(err.message); }
if(docs) {
docs.forEach(function(doc){
doc.edits.forEach(function(ed){
db.messages.find({_id:ed}, function (err, msg) {
// save stuff
});
});
});
}
});
This just seems wrong, but I'm unsure how else to proceed. Should I even bother with keeping an array of attached messages? I'm not married to the way I've set up my schema, either. If there is a better way to track relationships between them, or a better query to achieve this, please let me know.
Thanks
Does each message belong to only one headline? If so, you can store the headline id as part of each message. Then for each headline, do:
db.messages.find({headline_id: current-headline-id-here})
You could try using the $in operator for selecting a list of ObjectIds
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in