w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
MongoDB merge 2 very similar collections. Existing documents - update, new documents - insert
The most efficient in terms of queries would be to bulk update all the dates that need to be updated in one go per date and bulk insert all those documents that need inserting. Given you have 95% the same documents where you want to update A.dateLastSeen to be B.dateLastSeen. With single updates that would be: ~66,500 updates. Leaving ~3,500 inserts. Loading all B and A in memory - then processing is one possibility. You could create a bulk insert list and append anytime a doc from B is missing from A. Also a bulk update dictionary keyed by dateLastSeen containing a list of Documents to update. Depends on the probability of any matching dateLastSeen values to see if this is really worth it. Alternatively, simplify it an accept the high query cost and start processing B in batches o

Categories : Mongodb

How do I get the id of each doc when saving an array of documents with mongoose?
You can get arguments passed into any function by using the arguments object. For example: function argNum(){ console.log(arguments.length); } argNum('test',1,23,43); // Logs 4 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

Categories : Node Js

Mongoose how to populate referenced documents
For one category document, that could look something like this: // retrieve all feeds in the list and populate them mongoose.model('Feed') .find({ _id : { $in : category._feeds } }) // see text .populate('_articles') .exec(...); (I initially thought that the array passed to $in should be a list of ObjectId's, but apparently it's okay to pass an array of documents) EDIT: I think this works, too: mongoose.model('Feed') .populate(category._feeds, { path : '_articles' }) .exec(...);

Categories : Javascript

Transform an array of documents using mongoose
You can use a lean query so that an array of plain JS objects are returned from the query and then use map to transform the array: User.find({}).lean().exec(err, users) { users = users.map(function(user) { // transform user into newuser as needed. ... return newuser; }); });

Categories : Node Js

Populate method not returning documents - Mongoose
You're using Status in AccountSchema before it's defined. However, you should actually be using StatusSchema (the schema) instead of Status (the model) in the definition of AccountSchema anyway. Try this instead: var AccountSchema=new mongoose.Schema({ email:{type:String,unique:true}, password:{type:String}, name:{ first:{type:String}, last:{type:String}, full:{type:String} }, contacts:[Contact], status:[StatusSchema] });

Categories : Node Js

Use mongoose populate methods but still return ObjectID rather than documents
You need to pass the path to populate to the populate call instead of the model name: PlanModel.findOne({'_id':pid }, { 'plan':{ $slice: [ number, 1 ] }, 'plan.tasks':1,'plan.goal':1 }) .populate('plan.tasks', 'task_description') .exec( function(err, doc) { if(err){ callback(err, null); } else { callback(null, doc); } } )

Categories : Node Js

MongoDB-mongoose high cpu use when saving large documents in node.js
When you create a document in mongo, it allocates a portion of disk space to the document, with enough padding to accommodate document an estimated growth. If the document size exceeds the allocated space, mongo needs to move and reallocate new space for the document. This will keep happening as your document is growing. To avoid this, you will need to pre-allocate space. You do this by filling enough data into the document where mongo will allocate enough space to fit the max document size. In your case, when you first insert a new document, you will add enough host sub documents, to replicate your larger documents. After you insert that document, you can remove the hosts sub documents and insert the correct records. Now, this is not perfect. Mongo does not support transactions, so you

Categories : Node Js

In Mongoose Return only documents where parent value is matched and subdocument result is true
I think issue is the way you are structuring your entries. There is only one hex field per document, which means that it is impossible for a document to contain both values. To query what you want, each path name needs to have an associated array of hex values and percentages, so you could then execute an $and query that works.

Categories : Node Js

Insert or Update into MongoDB using mongoose.js
I don't think your notion of a single route that will either update an existing user or create a new one is a good idea. Instead, consider following the REST design: app.post('/api/users', createNewUser); app.put('/api/users/:userId', updateUser); createNewUser should just make a new user object with the proper attributes and call save on it. updateUser can do User.update({_id: req.params.userId}, fieldsToChange.... See if you can make that work to start and don't add complications like checking for already registered users until a simplistic create/update pair works OK and you feel confident. Then you can evolve your code to be more robust and realistic, but go step by step.

Categories : Node Js

Is it possible to add multiple documents in meteor through collection.insert()?
Batch insertion isn't yet possible with Meteor. Though you could make an iterator to help you insert documents in an array var docs = [{docNumber: 1},{docNumber: 2}]; _.each(docs, function(doc) { myCollection.insert(doc); }); It might be possible to do it on the server end, albeit with a bit of modifications to expose a bulk insertion method. The problem with this though is this code wouldn't work on the client end.

Categories : Database

Python - Pymongo Insert and Update Documents
Use upsert option: from pymongo import MongoClient cl = MongoClient() coll = cl["local"]["test2"] data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}] for d in data: coll.update({'_id':d['_id']}, d, True)

Categories : Python

How to insert multiple documents at once in MongoDB through Java
DBCollection.insert accepts a parameter of type DBObject, List<DBObject> or an array of DBObjects for inserting multiple documents at once. You are passing in a string array. You must manually populate documents(DBObjects), insert them to a List<DBObject> or an array of DBObjects and eventually insert them. DBObject document1 = new BasicDBObject(); document1.put("name", "Kiran"); document1.put("age", 20); DBObject document2 = new BasicDBObject(): document2.add("name", "John"); List<DBObject> documents = new ArrayList<>(); documents.add(document1); documents.add(document2); collection.insert(documents); The above snippet is essentially the same as the command you would issue in the MongoDB shell: db.people.insert( [ {name: "Kiran", age: 20}, {name: "John"} ]

Categories : Java

not able to insert documents into collection using mongodb java driver
The 'n' value from the getlasterror of an insert is always zero. (The 'n' value is what the WriteResult.getN() returns.) See this MongoDB Jira ticket: https://jira.mongodb.org/browse/SERVER-4381. Which has been closed in preference to a new insert, update, remove mechanism: https://jira.mongodb.org/browse/SERVER-9038 Long story short. You are not mad or missing anything. It is a "feature" of MongoDB that will hopefully finally be fixed with the 2.6 release. Rob. Edit: I modified your example slightly to print the saved document. Can you try running this version in your environment? import java.net.UnknownHostException; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com

Categories : Java

How can I safely insert mongo documents from json posts on my flask API?
I'm doing the same thing as you describe in my project(we don't do any validation, btw). If you users don't have to login into game, you don't have much options. You can use CSRF tokens, but this option is not safe enough. Other option is to generate this "requests" from application server, instead of client. This will ensure, that data is not compromised.

Categories : Mongodb

Mongoose converting stored UTC dates to local time?
The timestamps are stored timezone agnostically, as a unix timestamp. This timestamp will work across timezones, and node interprets it using your current timezone. You can retrieve the UTC value from the date object using the getUTC* methods such as get getUTCHours()

Categories : Node Js

SQL Insert many value 1 time or loop Insert each value many time which one is better?
Well, it depends on how many values you're actually inserting. Multi-row insert can have advantages if there are a lot of rows since you're not having to do a lot of round-trip calls to the database, something that can be important if your client and your DBMS are thousands of kilometers from each other. For only a few rows, or if your client/DBMS are co-located, you may find there's not a lot of difference.

Categories : PHP

insert values in table with out some columns that may change time to time
If you are looking for query, then use syntax: insert into tablename(columnlist seperated by comma) values (values list seperated by comma). For Example: insert into TableName(column1_name,column2_name) values(val1,val2);

Categories : Oracle

Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?
Express session is stored as separate storage and has limitations to what can be stored there. It cannot store prototype data (methods). Look at it more like key<>value storage. Reasons for this is that session can be stored anywhere (pretty much), such as: process memory; databases (mongodb); redis; etc. Because of this, once you put anything in session object and request is finished, express will take session data, parse it and stick into session store just as pure object. By default it is process memory, but as mentioned before - can be any other storages. So when next http request happens, session middleware will try to restore session using cookie (if it is used) data in request headers, and will ask session storage to provide data back. As it is already formatted - it will n

Categories : Node Js

Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.

Categories : Node Js

How to update only the non-existing documents and delete the old documents which doesnot exist now using mongoimport
Basically you want to keep only collection in your export right ? If so, take a look at the following options: --drop Modifies the restoration procedure to drop every collection from the target database before restoring the collection from the dumped backup. --upsert Modifies the import process to update existing objects in the database if they match an imported object, while inserting all other objects. If you do not specify a field or fields using the --upsertFields mongoimport will upsert on the basis of the _id field. More information on mongorestore

Categories : Mongodb

How to find documents by some conditions for its linked documents
As JohnnyHK commented, the type of query you want to do is a relational type query and document database such as mongodb simply do not support them. Fix your schema to put that tag data directly in the link schema (nesting or "denormalizing" from a relational standpoint, which is OK in this case), then you can query it: var LinkSchema = new Schema({ name: String, tags: [String] }); With that Schema, your query will work as you expect. To address the comments below. This is a document database. It's not relational. There are trade-offs. Your data is de-normalized and it gives you some scalability and performance and you trade off flexibility of queries and data consistency to get them. If you wanted to rename a tag, a relatively rare occurrence, you'd have to do a whopping 2 databas

Categories : Node Js

On SQL INSERT can I use the identity column for part of the insert data in another column at the same time?
From the documentation: After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement. This applies to all the other identity checkers. You should probably write a little SP to update the record immediately after your insert if this is what you need. Given that your primary_key appears to be some unusual composite of the ID and a varchar, you would also be best reviewing your data model. It's important to note the difference with @@IDENTITY and SCOPE_IDENTITY(): @@IDENTITY and SCOPE_IDENTITY return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.

Categories : SQL

Mongodb delete documents without associated documents
So each chat has a field visitor_id and you want to delete only visitors whose _id does not appear as a visitor_id in a chat? You would have to loop over all visitors, check last_activity for each, and if it is a candidate for deletion, do a find() on chats with that visitor's _id. If it turns up no documents, you can delete that visitor. When you iterate over all visitors, you do that with a MongoDB cursor (the result of a find()). The cursor is implemented in such a way that you can safely delete documents from the underlying collection while iterating over it. The trick is that you don't attempt to express everything in a single remove() call. You iterate, check, and delete as part of the iteration. You want to make sure that the find() inside the loop is very fast, by adding an ind

Categories : Mongodb

ECM : Migration of documents referencing other documents
(Disclaimer: I work for a company which have a lot of experience in these kind of migrations and we have special tools for them.) You need a mapping between the old (SharePoint) and new (LiveLink) paths of the documents. A simple two-step migration process is the following: Copy the documents from SharePoint to LiveLink and fill the mapping table during the migration. The links in LiveLink could be changed to point to a dummy LiveLink node, left empty. Fix the broken links in LiveLink with the mapping table.

Categories : Sharepoint

Mongodb : find documents including references to sub-documents [node-mongodb-native]
MongoDB doesn't support joins so you have to query for the User details separately. If you're using node.js, Mongoose provides a populate feature to help simplify this so you can do something like the following to pull in the user details: Files.find().populate('Users_id')

Categories : Mongodb

Set content div to zero initially
I would say, put your jquery in the to work as you would normally have it work and after that add this <noscript> tag in and of course you won't be able to make the animation in jquery anymore, but you'll make the div opacity 100% in the noscript tag then Edit: you could add the style in Joe's answer in the noscript tag, then you'll have alternate solutions :)

Categories : Jquery

tinymce - initially hide()
I really am not sure if I understand you right. Tinymce is an javascript iframe editor, you cant manipulate with it until its full load in page. You want to show editor on click inside the div? You could use this inline parameter: tinymce.init({ selector: "divID", inline: true }); Working example You want to hide the editor after some event? You could use this: $('#bottonID').click(function(){ tinymce.editors['divID'].hide(); }); Working example Or alternatively, try to use jquery tinymce: download Then manipulate tinymce like this: $(function() { $('textarea.tinymce').tinymce({ //your code }); }); If you could be more concrete,what you want to achieve, i could provide more exact answer.

Categories : Javascript

Why does the DataStateBehavior not update initially?
The problem here seems to be that the binding initially evaluates to null and thus doesn't fire the change notification required for the evaluation and state change. I've fixed it with the following subclass: public class FixedDataStateBehavior: DataStateBehavior { protected override void OnAttached() { base.OnAttached(); AssociatedObject.Loaded += (sender, routedEventArgs) => { var bindingExpression = BindingOperations.GetBindingExpression(this, BindingProperty); SetCurrentValue(BindingProperty,new object()); bindingExpression.UpdateTarget(); }; } } and used it like this: <FixedDataStateBehavior Binding="{Binding SelectedCamera}" Value="{x:Null}" TrueState="CameraSettingsUnselect

Categories : Wpf

ParticleSystem initially inactive
Send stopSystem to stop the particle emitter from emitting more particles. This will let existing particles continue until their lifetimes expire. Send resetSystem to start the particle emitter. This will kill all existing particles but make the system start emitting new particles. If you want to prevent the system from emitting any particles in the first place, set its emissionRate to 0 before adding it to its parent. Then set emissionRate to a positive number when you want it to emit particles. Take a look at the implementation of -[CCParticleSystem update:] method for details. Also, as far as I can tell, the parent doesn't start the particle system. Instead, the particle system is simply created in the active state. Did you try sending stopSystem to the system before adding it

Categories : IOS

How do you set a search box to be initially empty?
Remove the placeholder bit: placeholder="<?php _e("Search...") ?>" Will be like this: <input type="text" name="s" value="" />

Categories : HTML

addProximityAlert works initially
This is how I have added proximity: String geo = "geo:" + storeProximityData.getLatitude() + "," + storeProximityData.getLongitude(); Intent intent1 = new Intent(PROXIMITY_ALERT_HOME, Uri.parse(geo)); PendingIntent proximityIntent = PendingIntent.getBroadcast( sContext.getApplicationContext(), 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT); sLocationManager.addProximityAlert( storeProximityData.getLatitude(), // the // latitude // of // the // central // point // of // the alert region storeProximityData.getLongitude(

Categories : Android

insert two section at a time
You can create an instance of NSMutableIndexSet and add the indexes of the sections you want to add. Then you can pass that indexSet in -[UITableView insertSections:withRowAnimation:]. You DON'T need to call -[UITableView reloadData] right after: the insert method automatically does what's needed to display the new sections. You could even batch multiple changes and animate them at once by calling -[UITableView beginUpdates] before making the changes and finalizing the changes by calling -[UITableView endUpdates]. For more informations checkout the UITableView Class Reference.

Categories : IOS

Default Modelform field value initially set
class SubmitDomain(ModelForm): domainNm = forms.CharField(initial=u'Initial value') class Meta: model = Tld #Create form based off Model for Tld fields = ['domainNm',]

Categories : Django

UICollectionView animate cells in initially
Rather than setting the transform, change the center: - (UICollectionViewLayoutAttributes *) initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewLayoutAttributes* attributes = [super initialLayoutAttributesForAppearingItemAtIndexPath:indexPath]; CGPoint c = attributes.center; c.y -= self.collectionViewContentSize.height; attributes.center = c; return attributes; } Changing the transform can always cause problems with determining visibility, because doing so invalidates the frame property.

Categories : IOS

Hide div initially in jquery clone
clicks = 0; $('button').on('click', function () { $('div.loop').show(); if ($('div.loop').length < 5) { clicks++; if(clicks>1){ alert("more 1"); newLoopDiv = $($('div.loop')[0]).clone().appendTo(".container"); $('input', newLoopDiv).each(function (index, element) { $(element).attr('name', $(element).attr('name') + clicks); }); } else{ alert("asd"); newLoopDiv = $($('div.loop')[0]).appendTo(".container"); $('input', newLoopDiv).each(function (index, element) { $(element).attr('name', $(element).attr('name') + clicks); }); } } }); Replace and try this code with yours..Hope this is what you needed.. JSBIN DEMO

Categories : Jquery

Do something with checkbox both initially and on change using jQuery
Wrap it in a function and call it from both handlers: function someCheckboxfunction(lists) { lists = lists.split(";"); for(var i = 0; i < lists.length; i++) { var list = lists[i]; if($(this).is(":checked")) { container.prepend('<input type="hidden" name="lists" value="' + list + '">'); } else { container.find("input[type=hidden][value=" + list + "]").remove(); } } } Calling code $(document).ready(function() { container.find(("input[data-subscribe]").on("change", function() { someCheckboxFunction($(this).data("subscribe").toString()) }); var lists = container.find("input[data-subscribe]").data("subscribe").toString(); someCheckboxFunction(lists); });

Categories : Javascript

Set combo box initially to empty when using datasource
You would need to have an empty list item at a certain index, generally first (as with the usual "Please select...", and such kinds of defaults you see). You can use the Insert method of Items: cbPerson.Items.Insert("", 0); That might work, depending on which technology you're using, which you failed to specify. But whatever project type, the requirement is going to be very similar.

Categories : C

Expand the first row initially using MVC + Server Binding
Try this, Script function _GridItemDataBound() { this.expandRow(this.tbody.find("tr.k-master-row").first()); } View @(Html.Kendo().Grid<TwoModelInSinglePageModel.SampleModel>() .Name("grid12") .Columns(columns => { columns.Bound(p => p.studentclass).HeaderTemplate("<input id='selectall' class='chkbxq' type='checkbox' />").ClientTemplate("<input id='checkbox_#=inx#' class='chkbxq' type='checkbox' />"); columns.Bound(p => p.SampleDescription); columns.Bound(p => p.SampleCode); columns.Bound(p => p.SampleItems); }) .ClientDetailTemplateId("client-template") .AutoBind(true) .Events(events => events.DataBound("_GridItemDataBound")) .DataSource(dataSource =&

Categories : Kendo Ui

How to insert 2 users at a time in sql server?
Instead of trying to insert explicit values into an IDENTITY column you should use SCOPE_IDENTITY function in order to get the last IDENTITY value generated for current scope and session: SET NOCOUNT ON; CREATE TABLE dbo.Users( UserID INT IDENTITY(1,1) PRIMARY KEY, UserName NVARCHAR(200) NOT NULL ); INSERT INTO dbo.Users (UserName) VALUES ('John007'); SELECT SCOPE_IDENTITY() AS LastIdentityInserted#1; INSERT INTO dbo.Users (UserName) VALUES ('Mary008'); SELECT SCOPE_IDENTITY() AS LastIdentityInserted#2; Results: LastIdentityInserted#1 ---------------------- 1 LastIdentityInserted#2 ---------------------- 2 But if you want/need to insert more just one row then you should use the OUTPUT clause thus: DECLARE @inserted TABLE(UserID INT NOT NULL); INSERT INTO dbo.Users (UserNa

Categories : Sql Server

FullCalender not able to insert time into calender
I think the issue might be that the false value for the 'allDay' field in your PHP generated JSON is a String whereas FullCalendar is expecting a Bool. Try changing $buildjson as follows: $buildjson = array('id'=>"$eventtest",'title' => "$eventtest", 'start' => "$eventdt", 'end' => "$eventet", 'allDay' => false, 'backgroundColor' => "$eventc"); (note that falseis not surrounded in quotes)

Categories : PHP



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.