How to find all elements of array in database - node.js

I had taken this array
arr = ["1","2"]
And I want to find this id's are present in mongodb in user collection or not,
So how do I write query in mongoose for that?
user.find({'empid':'arr'},(err,res))
I am doing like this.

You should first loop through your array then run mongodb query to find item.
code should be some thing like this:
for(item in arr){
user.find({'empid':item},(err,res))
}

I think you are looking for the query operator "$in".
Here's how you can do it.
db.user.find({
"empid": {"$in": ["1", "2"] }
})
Try it on mongoplayground.net.

Related

Query find mongoose returns a document while its not $in array

I'm having issues with mongoose queries.
I am trying to check if a object with an Id is in an array of objects.
So my query is like
db.getCollection('adunits').find(
{_id: ObjectId("5bd9bc1ca4efae39d0b5a58e")},
{$in : ["5bf510156c154934150ef006","5bf5309e6c154934150f00a6","5bd9b874a4efae39d0b5a58d","5bf52a876c154934150efe4a"]}
)
As you can see, my ObjectId("5bd9...") IS NOT in the array. But my query returns the document with ObjectId("5bd9...").
Isn't the $in operator supposed to check if the _id in parameter is IN the array?
I wish it could return me a "0 fetched documents" because the id passed isn't in the array.
Thanks in advance
Your query is not right.
You can either find by id like so:
db.getCollection('adunits')
.find({_id: ObjectId("5bd9bc1ca4efae39d0b5a58e")})
to get a single document or use $in operator like so
db.getCollection('adunits')
.find({_id: { $in: ["5bf510156c154934150ef006","5bf5309e6c154934150f00a6",...]})
which will return documents which have one of the ids provided in the array.
You query condition finds adunits where _id = ObjectId("5bd9bc1ca4efae39d0b5a58e"), it returns the value that matches given condition. While $in operator should applied on a filed. Are you trying to achieve some thing like, find the documents that matches ids in given array.if yes , change your code to following. Visit mongodb official https://docs.mongodb.com/manual/reference/operator/query/in/.
db.getCollection('adunits').find(
{ "_id":
{ $in:
[ "5bf510156c154934150ef006",
"5bf5309e6c154934150f00a6",
"5bd9b874a4efae39d0b5a58d",
"5bf52a876c154934150efe4a"
]
}
});

How to return all matches from a list in MongoDB via Node.js application? [duplicate]

I have a process that returns a list of String MongoDB ids,
[512d5793abb900bf3e20d012, 512d5793abb900bf3e20d011]
And I want to fire a single query to Mongo and get the matching documents back in the same order as the list.
What is the shell notation to do this?
After converting the strings into ObjectIds, you can use the $in operator to get the docs in the list. There isn't any query notation to get the docs back in the order of your list, but see here for some ways to handle that.
var ids = ['512d5793abb900bf3e20d012', '512d5793abb900bf3e20d011'];
var obj_ids = ids.map(function(id) { return ObjectId(id); });
db.test.find({_id: {$in: obj_ids}});
This works fine for me in Robo 3T. No need to create any object and just use the list of ids.
db.getCollection('my_collection').find({'_id':{$in:['aa37ba96']}})
// categoryId comma separated "5c875c27d131b755d7abed86,5c875b0ad131b755d7abed81" in request
var ids= req.body.categoryId.split(',');
db.test.find({ categoryId: { $in: ids } });
If your final purpose is to get the document with the order by your pre-get ids list, you can just convert the query result into mapping(id as key, doc as value) , and then traverse the ids list to get the doc.

mongoosejs get _doc without loop

I have a question after performing a find() in mongoosejs.
Is there a better way of just getting the _doc-object without looping through the whole queryresult?
I'm searching for something like model.getDoc() but I can't find it.
Thanks
Ok, I found a solution by myself. Maybe it helps anyone:
var result = model.map(function(obj){
return obj._doc;
});
To get only specific fields of documents use string with field names (separated by space) as a second parametr, if you want ommit specific fields use "-" before field name
Model.find({}, '_doc', function(){...});
But this return documents like this:
{
_id: <object id>,
_doc: <some data>
}
If you want ommit _id field:
Model.find({}, '_doc -_id', function(... {}))
Or alternative syntax:
Model.find({}).select('_doc -_id').exec()

How to Join two collections in MongoDB and NodeJS with $lookup and DbRef?

If i have two collections where one of that have dbref, how is possibile to join using $lookup and dbref?
DBref is a BSON Object and you cannot make a lookup using its value.
BUT, there is a way to do it, transforming a DBRef object into an array.
I have written an answer a few months ago describing how to do it.
Short explanation
Say you have DBRef object like this :
myField: DBRef("otherCollection", ObjectId("582abcd85d2dfa67f44127e0")),
Use $objectToArray on myField like this
db.myColl.aggregate([
{
$project: {
transformedDBRef: {$objectToArray: "$myField"},
}
},
])
The result would be an array of two objects, one object for the reference, one for the ObjectId contained within the DBRef, each with a field "k" and a field "v". It will look like this:
transformedDBRef: [{"k" : "$ref","v" : "otherCollection"},{"k" : "$id","v" : ObjectId("582abcd85d2dfa67f44127e0")}
You can then grep the ObjectId. For the complete solution, please check the link above.

Query MongoDB for documents with non-empty intersection of arrays

So - I have a Heroku + Node + Express + MongoDB app in development, and I've been playing around all day trying to figure out how to get the mongo query I want. In a mongo collection, every document has a property 'fruits', which is an array of strings like
fruits : ['apple', 'orange', 'lemon']
The size and contents of fruits is arbitrary. I want to query the database for all documents whose fruits array has at least one element in common with another array which I provide when I make the query. How can I achieve this?
What I've tried so far centers around the $where query and some server-side JS. If I do something like
mongo.Db.connect(mongoUri, function(err, db) {
db.collection('Users', function(er, collection) {
collection.find( {$where: 'false' } ).toArray(function(err, matches){
console.log(matches)
...
});
});
});
I get an empty array - good! And if I change the false to true, I get the whole DB - also good! Things get less good with something like the following:
collection.find( {$where: function(){return false} } ).toArray(function(err, matches){...
I get the whole DB again! I thought this would pretty obviously return the same empty array as the very first example I gave above, as per the syntax presented at http://docs.mongodb.org/manual/reference/operator/query/where/
I was trying the above out just to see if I could get anything to work with $where, but further problems arise when I try to add server-side JS to the mix. I had a look at
http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/
and added the following to the system.js collection in my DB:
{
"_id": "isMatch",
"value": "function(){return false}"
}
and modified the above example with the line
collection.find( {$where: 'isMatch()' } ).toArray(function(err, matches){...
thinking that isMatch would now be in mongo's bag of tricks when it eval's the string (I assume it must be eval'ing the string), and the string syntax was the best bet from the playings around described above. Sadly this results in a console log of null - another flavour of wrong, I expected again an empty array.
Can anyone help me achieve the query I described above? I suspect I can work out the nitty gritty myself if you kind folks can help me understand 1. How to use the function syntax instead of the string syntax for $where, and 2. How to correctly declare a JS function in system.js for use with $where. Thanks in advance!
Your $where queries work fine when I try them in the shell, but you don't need to use $where for this query. Instead, you can use an $in that targets your fruits field to find docs that contain at least one matching fruit:
var fruits = ['apple', 'orange', 'lemon'];
db.test.find({fruits: {$in: fruits}});
Don't quite seem to know what was the case in 2013, but now I think you have to use $elemMatch along with $in that targets your fruits field to find docs that contain at least one matching fruit:
var fruits = ['apple', 'orange', 'lemon'];
db.test.find({fruits: {$elemMatch: {$in: fruits}}});

Resources