How to check if document exist with particular field in mongodb - javascript

I have an array of users and I have one collection named users. Now I want to find the documents which has user_id equals to users from Array. And if that user id doesn't exist then no action taken. I'll loop through array to get one user id at a time. Now my concern is how to find the document with that particular user_id in MongoDB
Output I want:
Array a= [1,2,3,4,5]
document with user_id=1
document with user_id=2
document with user_id=3 like that
Thanks for help!!!

You can use $in operator. For more information https://docs.mongodb.com/manual/reference/operator/query/in/
For example
db.collection.find({user_id:{$in:[1,2,3,4,5]}})

Related

mongodb count unique constraint on 2 fields

On my car mongodb collection I have user_id and default_car fields. One user can have only one default car but can have multiple non-default cars. For instance this value should be valid :
[{user_id:1,default_car:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:false},{user_id:2,defaut_tool:false}]
user with id 1 has only one car but user with id 2 has 3 cars and one of them is the default one. This example should be invalid :
[{user_id:1,default_car:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:true},{user_id:2,defaut_tool:false}]
What kind of constraint Do I need to define ? I use mongoose on nodejs.
If you are looking to satisfy a uniqueness constraint within MongoDB, then you will want to look into unique indexes.
In your particular situation, it sounds like the uniqueness constraint should be enforced is that each specific user_id cannot have more than one default_car. Therefore you your index should also be a partial index. Specifically the index should probably resemble the following:
db.<collectionName>.createIndex({_user_id:1},{unique:true, partialFilterExpression:{default_car:true}})

How to efficiently query object with large field array?

So basically I have an object schema that has an array field that will hold ids for objects inside a different collection. This array field has the potential to have thousands of ids inside of it. I have been omitting this field using .select(["-fieldName"]); in my queries up till now but I need to include it in my query if I wanna add on to it.
I would assume querying an object with such a large field is costly in performance so therefore my question is how can I efficiently query such an object?
I would like to just omit this field in my query but then I can't add ids into it.
If you just want to add an item to the array field you can use the $push operator.
collection.updateOne(query, { $push: { arrayField: value } });

How to assign users to a group and sort them using firestore reference field type

I have a collection of employees that has data sent to it. Right now there is 4 employees but eventually there will be many more.
I want to add a grouping feature so that the user can sort the employees by their group. I am trying to find the best way to assign these employees groups and I found the reference field type in cloud firestore and thought I could use it to solve my problem. But I am stuck and not sure the most efficeient way to use it to link employees to a group.
This is my database. Right now I have the employees doc (ex. 2569) and inside that is a sub-collection with 2 documents in itself.
So end goal is to assign employees groups and then be able to sort and display them separately. Right now I have the group name assigned in articles/group -> groupName: "example".
(display them hopefully with ".Where( "groupName" "==" "example" ) somehow in code without hard-coding the group name. The group name will be created by the user so it could be anything)
Is what I am doing a good start? I know this question is a little odd but I am stuck and could really use some pointers on where to head next.
A collection group query would allow you to query all articles regardless of which employee contained them:
db.collectionGroup('articles')
.where('groupName', '==', 'X')
.get()
This would match documents in any collection (i.e. employees) where the last part of the collection path is articles. If you would like to find the employees who belong to a certain groupName, you may want to find the parent by retrieving the collection this DocumentReference belongs to.
Once you have the parent of the CollectionReference, you will get a reference to the containing DocumentReference of your subcollection.

How to add auto increment to existing collection in mongodb/node.js?

Is there any methods or packages, that can help me add auto increments to existing collection? Internet full of information, about how to add AI before you create collection, but I did not find information on how to add AI when collection already exist...
MongoDB does not have an inbuilt auto-increment functionality.
Create a new collection to keep track of the last sequence value used for insertion:
db.createCollection("counter")
It will hold only one record as:
db.counter.insert({_id:"mySequence",seq_val:0})
Create a JavaScript function as:
function getNextSequenceVal(seq_id){
// find record with id seq_id and update the seq_val by +1
var sequenceDoc = db.counter.findAndModify({
query:{_id: seq_id},
update: {$inc:{seq_val:1}},
new:true
});
return sequenceDoc.seq_val;
}
To update all the already existing values in your existing collection, this should work (For the empty {}, you can place your conditions if you want to update some documents only):
db.myCollection.update({},
{$set:{'_id':getNextSequenceVal("mySequence")}},{multi:true})
Now you can insert new records into your existing collection as:
db.myCollection.insert({
"_id":getNextSequenceVal("mySequence"),
"name":"ABC"
})
MongoDB reserves the _id field in the top level of all documents as a primary key. _id must be unique, and always has an index with a unique constraint. It is an auto-incrementing field. However, it is possible to define your own auto-incrementing field following the tutorial in the MongoDB documentation.
Tutorial link: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

Use array or JSON to keep track of unique list

I have an object in Parse .com database that can receive thumbs up votes. I want to keep track of which users have provided a thumbs up to prevent the same user doing it again. I am thinking of adding a field to my object called "voters" that will hold the list of voting users.
Should this be an array of usernames or a JSON with keys as the usernames?
Why would I use an array if i could use a json map and do O(1) lookup of the names on the keys?
ie object.voters[uername] = undefined then no votes?
Use Array if you need just the name of the voter .
Use Json if you need more info than just the name .
Why is that if u need just the name just making an array with the voter names first will be easy second it will be faster t process .
but if you need something like
voter={"name":"foo","age":"25"}
as you see we can use the powerof json to save multiple info about one user and anyway each voter must be within a single array so you can iterate over them
UPDATE---
to find the index of a name in an array just use array.indexOf("the name") what this will return is the index number of the name if the name doesnt exist it will return just -1 so a simple if else can handle this
UPDATE---
And here i found a performance test to compare which is faster to lookup whitin an array or an object and seems arrays still win this.
And here is another source for reading

Categories

Resources