w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Finding first 20 documents from collection in mongodb
On the MongoDB shell you can do: db.collectionName.find( { city: "London" } ).skip( 20 ).limit( 20 ); To show the results from document 21 to 40. Please look at limit and skip: http://docs.mongodb.org/manual/core/read/#limit-the-number-of-documents-to-return I also strongly suggest you go over a tutorial: http://docs.mongodb.org/manual/tutorial/getting-started/

Categories : Mongodb

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

Is it possible to include other documents from the same collection in MongoDB's aggregate() function?
As at MongoDB 2.4, the Aggregation Framework does not support fetching additional documents into a pipeline or referencing documents relative to the current document. You will have to implement these sort of calculations in your application logic. You may want to upvote and watch SERVER-4437 in the MongoDB Jira issue tracker; this feature suggestion is to add support for windowing operations on pipelines.

Categories : Mongodb

PHP MongoDb, find all referenced documents when collection is indexed array
I don't quite see why you have such a complicated structure. Particularily the "0" and "1" keys are problematic, especially dealing with PHP as it doesn't really like arrays with numerical string keys. The $ref/$id fields come from MongoDBRef, which should avoid as they don't provide you with any functionality. You should just have: { "_id": ObjectId("5188deba4c2c989909000000"), "_type": "Model_Discs", "title": "really cool cd", "referencedBy": [ ObjectId("4e171cade3a9f23359e98552"), ObjectId("5045c3222b0a82ec46000000") ] } Then you can simply query with: db.collection.find( { referencedBy: new ObjectId("5045c3222b0a82ec46000000") } );

Categories : PHP

fetch documents from mongodb collection by querying nested dictionary in mongo
You can use the $exists operator and dot notation to do this, but you need to build up your query dynamically like this (in the shell): var user = 'abc'; var query = {}; query['user_details.' + user] = { $exists: true }; db.coll.find(query);

Categories : Python

mongodb - add column to one collection find based on value in another collection
In MongoDB, the simplest way is probably to handle this with application-side logic and not to try this in a single query. There are many ways to structure your data, but here's one possibility: user_document = { name : "User1", postsIhaveLiked : [ "post1", "post2" ... ] } post_document = { postID : "post1", content : "my awesome blog post" } With this structure, you would first query for the user's user_document. Then, for each post returned, you could check if the post's postID is in that user's "postsIhaveLiked" list. The main idea with this is that you get your data in two steps, not one. This is different from a join, but based on the same underlying idea of using one key (in this case, the postID) to relate two different pieces of data. In gene

Categories : Mongodb

Better way to move MongoDB Collection to another Collection
You could use a MapReduce job for this. MapReduce allows you to specify a out-collection to store the results in. When you hava a map function which emits each document with its own _id as key and a reduce function which returns the first (and in this case only because _id's are unique) entry of the values array, the MapReduce is essentially a copy operation from the source-collection to the out-collection. Untested code: db.runCommand( { mapReduce: "mongo_collection", map: function(document) { emit(document._id, document); }, reduce: function(key, values) { return values[0]; }, out: { merge:"mongo_his_collection" } }

Categories : Mongodb

java garbage collection does a <(major collection:mark and sweep> every time it does a
I would try removing all the settings you have so that you have the absolute minimum and you are less likely to get a strange interaction between settings Try just -Xmx16g -XX:+UseConcMarkSweepGC and monitor it using jstat

Categories : Java

Bulk Collect into is storing less no of rows in collection when using LIMIT?
The problem is when you are looping through with limit set to 100, you are dropping previous fetch results. So 3 times 100 rows are fetched which get dropped everytime you loop through and in last turn 66 are fetched, so you get result as 66. You need to accumulate all the results to get correct count. For correct usage of bulk collect with limit, see this example: PROCEDURE process_all_rows (limit_in IN PLS_INTEGER DEFAULT 100) IS CURSOR employees_cur IS SELECT * FROM employees; TYPE employees_aat IS TABLE OF employees_cur%ROWTYPE INDEX BY PLS_INTEGER; l_employees employees_aat; BEGIN OPEN employees_cur; LOOP FETCH employees_cur BULK COLLECT INTO l_employees LIMIT limit_in; FOR indx IN 1 .. l_employees.COUNT

Categories : SQL

'Implicit' Garbage Collection doesn't reduce memory footprint. GC.Collect() does
The garbage collector is actually pretty intelligent. It does not collect memory if it doesn't have to, and that provides it some optimization flexibility. It keeps open the option of resurrecting the objects that require finalization but that are not yet finalized. As long as the memory is not required, the garbage collector thus does not force the finalization, just in case it can resurrect those objects.

Categories : C#

Create a collection of sub collection from a given Collection (Group By) in Java
Probably this is what you need until java 8 closures comes HashMap<Integer, DateTileGrid> dataGridMap = new HashMap<>(); for (Date date: dateList) { int year = date.getYear(); //Deprecated.. use something better DateTileGrid dataGrid = dataGridMap.get(year); if(dataGrid == null){ dataGrid = new DateTileGrid(); dataGrid.setCurrentYear(year); dataGrid.setDateTiles(new ArrayList<Date>()); dataGridMap.put(year, dataGrid); } dataGrid.getDateTiles().add(date); } //Here is your result ArrayList<DateTileGrid> result = new ArrayList<>(dataGridMap.values());

Categories : Java

Get empty collection of embedded documents
I had exactly the same problems: saving was no problem but fetching the embedded document was. Turned out it was a "Symfony" caching problem (also on app_dev.php). Have you tried to remove your cache, this worked for me!

Categories : Mongodb

Find documents that DON'T have a string in a collection
You need to create an index for this type of query. In the index you should flatten your OptOut collection so you can create queries on it. More on this here: How to query items from nested collections in Raven DB? EDIT It seems that this can be answered with a simple LuceneQuery w/o having to explicitly create and index. var users = session.Advanced .LuceneQuery<Person>() .Where("OptOut:* AND -OptOut:" + newsLetterType) .ToList(); EDIT 2 You will need to create this index: from doc in docs.People select new { OptOut = doc.OptOut.Count==0 ? "" : doc.OptOut} To include person documents having no OptOut values. It is frustrating how this is not available in the Query (typed client) but we can continue with that discu

Categories : Linq

How to get a collection with some some fields excluded from some documents?
I would set up two subscriptions, one for a person's characters and another for all characters (which removes the fields you don't want published). The results will get merged. A little more information per the DDP spec: The client maintains one set of data per collection. Each subscription does not get its own datastore, but rather overlapping subscriptions cause the server to send the union of facts about the one collection's data. For example, if subscription A says document x has fields {foo: 1, bar: 2} and subscription B says document x has fields {foo: 1, baz:3}, then the client will be informed that document x has fields {foo: 1, bar: 2, baz: 3}. If field values from different subscriptions conflict with each other, the server should send one of the possible fi

Categories : Mongodb

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

How do I fill a collection with millions of dummy documents without a million inserts?
While you could just write code to insert documents using your favorite programming language (as many of the drivers offer techniques to insert documents in batches via an array structure), I'd suggest you consider creating either a JSON file or a CSV file containing the structure of your documents (maybe in multiple files if necessary for the import to work), and then using mongoimport, import all of the data. http://docs.mongodb.org/manual/reference/program/mongoimport/ This way, you can create the file(s) once, and run the import directly from the database server without installing extra software/platforms/node/etc. If you wanted to use Node.JS, you can use insert (documentation) and simply pass in an array of documents. I'd suggest doing it batches of some size far less than one mil

Categories : Node Js

Meteor: Embed documents inside a document or separate them into each collection object and link them?
Separate collections for students and classrooms seems more straightforward. I think just keeping a 'classroom' or 'classroomId' field in each student document will allow you to join the two collections when necessary.

Categories : Mongodb

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

Count MongoDB collection row
I've not used the Node.JS driver at all, but looking at the documentation, it appears that Collection() has a count function on it: // Assuming DB has an open connection... db.collection("my_collection", function(err, collection) { collection.count(function(err, count)) { // Assuming no errors, 'count' should have your answer } }); Does that help at all? As for the second part of your question, I'm not entirely sure what you're asking but here are a couple of ways of getting your data: Using the toArray() function to give you an array of all documents (see docs): collection.find().toArray(function(err, docs) { // 'docs' should contain an array of all your documents // 'docs.length' will give you the length of the array (how many docs) }); Using the each() fu

Categories : Node Js

How to unshard a collection on mongoDB?
If you check out this JIRA ticket, there's a very detailed discussion of how to safely unshard (and re-shard, using a different key) collections in mongoDB: https://jira.mongodb.org/browse/SERVER-9845 The method described in that ticket involves migrating your data to a single shard, removing the metadata, and then re-sharding. If you'd rather drop the data entirely, then rebuild, you should be able to skip the migration step. You will still have to re-start your mongos and shard servers for the change to go into effect.

Categories : Mongodb

can't shard a collection on mongodb
The problem initially was that you did not have a hashed index what you proposed to use for sharding this is the error message is about. After the first error message, when you created an index which is { "v" : 1, "key" : { "LOG_DATE" : 1 }, "ns" : "mydb.c2", "name" : "LOG_DATE_1" } You still just have an ordinary index which is not a hashed one. If you would do this : db.c2.ensureIndex({LOG_DATE: "hashed"}) Instead of this : db.c2.ensureIndex({LOG_DATE: 1}) Than would be a hashed index. As you can see in the output of the db.system.indexes.find() on the other collection you have a hashed index for the timestamp i assume this is the shard key for that collection. So if you have no data in the c2 collection: db.c2.drop() db.createCollection('c2') db.

Categories : Mongodb

MongoDB - aggregate to another collection?
The Aggregation framework currently cannot be outputted to another collection directly. However you can try the answer in this discussion: SO-questions-output aggregate to new collection The mapreduce is way slower and I too have been waiting for a solution. You can try the Hadoop to Mongodb connector, which is supported in the mongodb website. Hadoop is faster at mapreduce. But I do not know if it would be well suited in your specific case. Link to hadoop + MongoDB connector All the best.

Categories : Mongodb

Backbone.js - extending a model(in collection) using parse method not getting the updated collection
That is because the response in done is not a Collection. It is just an object from the response.. Log c which is an updated collection c.done(function(data){ console.log(c); //Will be the updated collection }) Also listening to the event is a cleaner approach than using promised methods. initialize: function() { this.$el.html(this.template); this.c = collection; this.listenTo(this.c, 'sync', this.logCollection); this.c.fetch(); //fetching the data }, logCollection: function() { console.log(this.c); // This will log the collection }

Categories : Jquery

Hibernate deletes Lazy loaded many-to-many collection when a get call is made on the collection
I guess this is causing an issue private Set<Role> roles = new HashSet<Role>(0); @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "USERROLEMAP", joinColumns = { @JoinColumn(name = "USERID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "ROLEID", nullable = false, updatable = false) }) public Set<Role> getRoles() { return this.roles; } It should be private Set<Role> roles; @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinTable(name = "USERROLEMAP", joinColumns = { @JoinColumn(name = "USERID", nullable = false, updatable = false) }, inverseJoinColumns = { @JoinColumn(name = "ROLEID", nullable = false, updatable = false) }) public Set<Role> getRoles() { if(roles

Categories : Java

Returning a Collection from a method that specifies that it returns Collection
Reason for the error The reason the exception is raised is because Collection<ParentClass> can have any object that extends ParentClass added to it. For example an instance of the following class could be added to it public class OtherChildClass extends ParentClass{ } But because the "real" collection is a Collection<ChildClass> this would raise an error. Or even if you added a ParentClass to it it would raise an error. All in all not good. Solution This can be solved however by using Collection<? extends ParentClass> in your type declaration. The meaning of this is that you are returning a Collection that is declared as containing some class that could be cast to ParentClass and is called contravariance. Such a collection cannot have new objects added to it (with the

Categories : Java

Convert scala.collection.immutable.Vector to java.util.Collection
You need to call asJavaCollection to do the conversion, this should work: import scala.collection.JavaConverters._ var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition()) request.setAttributeDefinitions(attrDefs.asJavaCollection) As an alternative, you can use import scala.collection.JavaConversions._ to not have to call asJavaCollection. However, I find that it makes what the code is doing more readable to call the method. Here's the alternate example: import scala.collection.JavaConversions._ var attrDefs = Vector(new AttributeDefinition(), new AttributeDefinition()) request.setAttributeDefinitions(attrDefs)

Categories : Java

Linq query to get filtred main collection and each list in result in that collection
This should be done in View Model (or Dto) layer, first, define your view models: public class RestaurantVM { public int Id { get; set; } public string Name { get; set; } public City City { get; set; } public List<MealVM> Meals { get; set; } } public class MealVM { public int Id { get; set; } public string Name { get; set; } public DateTime Date { get; set; } public int Price { get; set; } public int Number { get; set; } public int Kind { get; set; } } Then you can write LINQ like below: var restaurantVMs = db.Restaurants .Include(rest => rest.Meals) .Where(rest => rest.City.Name == city) .AsEnumerable() .Select(r => new RestaurantVM(){

Categories : C#

Wrong collection.length when passing JSON array to Backbone Collection
If you dump one of the items returned by Google Spreadsheets, you will see that the data is nested in multiple objects, something like this { "id":{"$t":"https://spreadsheets.google.com/feeds/list/..."}, "updated":{"$t":"2013-07-30T12:01:24.000Z"}, "category":[{"scheme":"...","term":"..."}], "title":{"type":"text","$t":"ACIW"}, "content":{}, "link":[{"rel":"self","type":"application/atom+xml","href":"..."}] } In a Fiddle http://jsfiddle.net/nikoshr/kHBvY/ Note how the id property is wrapped in an object "id":{"$t":"https://spreadsheets.google.com/feeds/list/0AjbU8ta9j916dFdjSVg3YkNPUUJnWkZSWjBDWmZab3c/1/public/basic/cokwr"} Backbone collections don't allow duplicates and duplicates are determined based on their id. All your items are considered duplicates and

Categories : Javascript

Meteor.js: having multiple subscriptions on one collection enforce storage results in one local collection(Workarounds?)
If you want your client side collection to have a different name from the server side collection you can not just return a collection cursor. This can be done in the publish function though like this: Meteor.publish("details", function (id) { //details here matches the subscribe request var self = this; self.added( "details", id, collection.findOne({_id: id}); //details here tells the client which collection holds the data self.ready(); }); This will not be reactive but can be made that way by using observe as in the counts by room example at http://docs.meteor.com which is explained in detail here How does the messages-count example in Meteor docs work?. While this answers your question of how to get a specific name for a collection without having that collection on the serv

Categories : Meteor

Mongodb. Cannot find defined collection in C#
You must add a Class like code below var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("testdb"); // "testdb" is the name of the database // "Users" is the name of the collection var collection = database.GetCollection<Entity>("Users"); // var searchQuery = Query.EQ("firstname", "Tom"); var cursor = collection.FindAll(); what is Entity? -It's the class i'm telling yout about to get and set fields inside this collection. In my case,it should look like this : class Entity { public ObjectId Id { get; set; } public string firstname { get; set; } public string lastname { get; set; } }

Categories : C#

mongodb querying collection starting with _
Place it in quotes and use the getCollection method. See this article Example To create a collection _foo and insert the { a : 1 } document, use the following operation: db.getCollection("_foo").insert( { a : 1 } ) To perform a query, use the find() method, in as the following: db.getCollection("_foo").find()

Categories : Mongodb

Advice on collection schema for MongoDB
If you need fast queries: I think your schema is more or less Ok. If you need fast updates: I would instead refer to the parents using their _id to convert player collection into people collection. In this way if parents change you only update one document and not as many as players having this parent. Keep in mind that, even if you need fast queries, this is not very maintainable because you may have, as you say, duplicate data and this can lead to data inconsistencies.

Categories : Mongodb

can I save every objects in one collection in mongodb?
Because MongoDB collections are heterogeneous, it is technically possible to store documents in one collection which have nothing to do with each other. But having separate collections for separate classes of documents has the advantage that you can easily isolate these documents from each other. In your example, where you have animals and ships, it is unlikely that you will have search queries which are supposed to return animals AND ships. Most queries will likely return one or more documents either from the set of animals or from the set of ships. Imagine in your example, that you would like to have a list of all animals which are different types of Sharks. So you do db.collection.find({type:"Shark"}. But unfortunately you weren't aware that there is also a type of sailboat named "Sh

Categories : Mongodb

Setting TTL for collection using Doctrine MongoDB ODM
You're mixing index options with the keys parameter. The Index annotation also has an options parameter. See the example in the Index annotation docs: <?php /** * @Document( * indexes={ * @Index(keys={"username"="desc"}, options={"unique"=true}) * } * ) */ class User { //... } This is equivalent to passing {unique: true} as the second argument db.collection.ensureIndex(). You can replace unique with expireAfterSeconds to create a TTL index.

Categories : PHP

get Result only from one Collection mongodb/Symfony 2
I solved like that: $result = array(); $return = array(); $result = $cties_list->toArray(); foreach ($result as $val) { array_push($return, $val->getCityName()); }; If there is any other suggestion, don't hesitate

Categories : Symfony2

mongoDB select from collection with relation
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 ] } } )

Categories : Mongodb

Pymongo Not creating collection in mongodb
The collection will not be created until you add data, this is since collections and even databases in MongoDB are done lazily by default. If you wish to explicitly allocate a collection eagerly then use: http://api.mongodb.org/python/current/api/pymongo/database.html#pymongo.database.Database.create_collection

Categories : Python

Indexing MongoDB collection in Java
You should construct a new DBObject that represents your index. See the code bellow: DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get(); DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection"); collection.ensureIndex(index2d);

Categories : Mongodb

How to obtain a MongoDb collection in NodeJS
If you look at the code for Database, currently around line 456, you'll see that the only difference between the two in the way you've used them is how the collection object is returned. If you specify a callback, then it's returned that way, otherwise, it's returned as the value to the function. If you set the options however and specifically the option strict to true, you need to use the callback. When strict is set to true, the collection is verified before continuing (asynchronously). Given that collections can be created dynamically (and usually are upon first use), there often isn't need to use strict mode. So, it's really matter of personal coding preference otherwise. There is normally no activity to the database when creating a Collection object via: db.collection('collectionn

Categories : Node Js

Group by dates in mongodb collection
db.aggregate([ {$match: {uid: "0001", logTime: {$gte: ISODate('Mon Dec 27 2010'), $lt: ISODate("Mon Dec 29 2010")}}}, {$project: {day: {'$dayOfMonth': '$logTime'},month: {'$month':'$logTime'},year: {'$year':'$logTime'} } }, {$group: { _id: {day:'$day',month:'$month',year:'$year'}, log: {$push:{logPath:'$logPath'}} }} ]) Something like that should do the trick. If you want to group by only month then you can take out the day field from the _id of the $group. There is another way of doing dates but I must admit this way is probably the easiest at the moment.

Categories : Mongodb



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