w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Find oldest post — WordPress
Yes, you're right. Use count. Suppose the total posts is 5 for $total_posts = count($posts);. You'll have to check your $counter for total - 1 as the array is $posts[0], $posts[1], $posts[2], $posts[3], $posts[4]. <?php if ( have_posts() ) : $counter = 0; $total_posts = count($posts) - 1; while ( have_posts() ) : the_post(); if( $counter == $total_posts ) { ?> <div class="container"><?php // CUSTOM CODE FOR LAST ARTICLE ?></div> <?php } else { ?> <div class="container"><?php // CUSTOM CODE FOR THE REST OF ARTICLES ?></div> <?php } $counter++; endwhile; endif; Note that you only need to open <?php

Categories : PHP

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

Find only youngest element in array
I've managed this with editing my data. I just copy the last status to a own property. But I think this might be the solution: https://github.com/elasticsearch/elasticsearch/issues/3022

Categories : Elasticsearch

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#

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

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

C programming, how would I find the oldest date in an array of date structures?
Ok, first I should tell you that this is a question that can have many many many correct answeres. You could instead of creating an array of strucutures studentInfo, create a tree and whenever you insert a new node into the tree keep the root node as the oldest among many other solutions. Anyway for your simple case, a simple solution could be as follows Step 0. You want to find studentInfo *oldest = records; Step 1. Iterate through the array studentInfo *traveler; for(traveler = records; i<recNum; i++, traveler++) Step 2. Compare the date from oldest and traveler. if(oldest->birthDate.year > traveler->birthDate.year && oldest->birthDate.month > traveler->birthDate.month && oldest->birthDate.day > traveler->birthDate.day) Step

Categories : C

Include related data from second collection in collection.find
Don't use $regex unless its a direct (with the mongodb $regex) syntax. This should work: searchFoo = function(query) { var re = new RegExp(query, "i"); return FooCollection.find({ name: re }); }; as should this: searchFoo = function(query) { return FooCollection.find({ name: { $regex: query, $options: "i" } }); }; Additionally to link up your bar query do a transform instead of regex: FooCollection.find({name:"SOMENAME"}, {transform:function(doc) { if(doc.barId) doc.bar = FooCollection.findOne(doc.barId) return doc; }}); This should give you the result (after a fetch or if you parse through the cursor) [{ name: SOMENAME, barId: MONGO_ID, bar : { name: ANOTHERNAME} }] More information about transforms can be found in the meteor do

Categories : Meteor

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

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

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

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

How to use existing mongodb collection in rails3.2
it should be plain and simple if I understood your question. say you have a model that uses mongoid class Model include Mongoid::Document #define fields here end then in controller @records = Model.all then you should get an array of records

Categories : Ruby On Rails

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

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

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

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

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

Get objects in a collection with an array of id's in mongoDB
Maybe this is more like it? exports.findItemsByUserId = function(req, res) { var userId = "51e101df2914931e7f000003"; //Just for testing var user = db.users.find({"_id": userId}); var items = db.items.find({'_id': {'$in' : user.useritems}}); res.send(items.toArray()); };

Categories : Node Js

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

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

MongoDb for collection of production data
MongoDB can definitely be used for your scenario. Look at http://www.slideshare.net/pstokes2/social-analytics-with-mongodb, http://docs.mongodb.org/manual/use-cases/pre-aggregated-reports/ or Real-time statistics: MySQL(/Drizzle) or MongoDB? for more on this topic

Categories : Node Js

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

MongoDB sharded collection not rebalancing
In MongoDB when you go to a sharded system and you don't see any balancing it could one of several things. You may not have enough data to trigger balancing. That was definitely not your situation but some people may not realize that with default chunk size of 64MB it might take a while of inserting data before there is enough to split and balance some of it to other chunks. The balancer may not have been running - since your other collections were getting balanced that was unlikely in your case unless this collection was sharded last after the balancer was stopped for some reason. The chunks in your collection can't be moved. This can happen when the shard key is not granular enough to split the data into small enough chunks. As it turns out this was your case because your shard ke

Categories : Mongodb

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

Update/remove subdocument in MongoDB collection
You need to use $elemMatch to match inside an array. The query rules in MongoDB specify that for conditions on array elements, any array element where any of the conditions matches is considered a match. With $elemMatch, all conditions need to match on the same element.

Categories : Mongodb

mongodb: sharded collection count keep reducing
quote: Just because you set balancer state to "off" does not mean it's not still running, and finishing cleaning up from the last moveChunk that was performed. You should be able to see in the config DB in changelog collection when the last moveChunk.commit event was - that's when the moveChunk process committed to documents from some chunk being moved to the new (target) shard. But after that, asynchronously the old shard needs to delete the documents that no longer belong to it. Since the "count" is taken from meta data and does not actually query for how many documents there are "for real" it will double count documents "in flight" during balancing rounds (or any that are not properly cleaned up or from aborted balance attempts). Asya

Categories : Mongodb

Add field that is unique index to collection in MongoDB
Try creating a unique sparse index: db.users.ensureIndex({username:1},{unique:true,sparse:true}) As per the docs: You can combine the sparse index option with the unique indexes option so that mongod will reject documents that have duplicate values for a field, but that ignore documents that do not have the key. Although this only works for documents which don't have the field, as opposed to documents that do have the field, but where the field has a null value.

Categories : Mongodb

Can I require an attribute to be set in a mongodb collection? (not null)
In Mongoose, you can use a validator to check if a field has been set before you save it. As far as I know, there is no way of specifying on a Schema that a field is required, so it requires a little more boilerplate code.

Categories : Mongodb

How to add data to a (heavily) nested collection in MongoDB
You did not say what you actually tried. To access a sub-document inside an array, you need to use dot notation with numeric indices. So to address the Name field in your example: Segments.Devices.0.Interfaces.0.Name Did you try that? Does it work?

Categories : Python

exporting mongodb collection into csv having list of subdocuments
I don't think that the CSV format allows you to split up a single document as multiple documents, as this is something that you would need if you have nested documents. It would most definitely not create multiple fields for each sub-document as you are expecting. If you want to do that, then you can quite easily write your own CSV exporter which allows you a lot more flexibility anyway.

Categories : Mongodb

Creating MongoDB capped collection is too slow
Capped collections are preallocated when created and with ext3 that will block. Ext4 or XFS is preferred[1] because they implement posix_fallocate, which means MongoDB can allocate large files quickly. [1] http://docs.mongodb.org/manual/administration/production-notes/

Categories : Database

Update embedded collection element MongoDB
This is the code you need: var update = Update.Set("Comments.$.Text", "new comment text"); var query = Query.And( Query<User>.EQ(u => u.Id, userId), Query<User>.ElemMatch(u => u.Comments, eq => eq.EQ(c => c.Id, commentId))); userCollection.Update(query, update);

Categories : C#

MongoDB cross-collection query with casbah
Of course you can do this in casbah - remember db.flags.distinct returns an iterable that should be converted implicitly to a list for use in $in. Heres a test example for you: import com.mongodb.casbah.Imports._ val db = MongoClient()("casbahTest") val customers = db("customers") val flags = db("flags") customers.drop() flags.drop() // Add some customers customers += MongoDBObject("_id" -> 1, "name" -> "foo") customers += MongoDBObject("_id" -> 2, "name" -> "bar") customers += MongoDBObject("_id" -> 3, "name" -> "baz") // Add some flags flags += MongoDBObject("cid" -> 1) flags += MongoDBObject("cid" -> 3) // Query // In JS: db.customers.find({id: {$in: db.flags.distinct("cid", {})}}) // Long hand: customers.find(MongoDBObject("_id" -> MongoDBObject("$in"

Categories : Mongodb

MongoDB query comparing 2 fields in same collection for php
The SERVER-7623 ticket that Mason referred to in his comment above will definitely support this, after it is implemented. For the time being, you will have to resort to the $where query operator, which takes a string of JavaScript code and allows you select documents where the expression would evaluate to true (the current document is available as this). There are examples in the documentation that cover your exact use case. Be aware of the performance caveats of $where (e.g. regarding indexes), which are also discussed there.

Categories : PHP

Using the C# driver Is their a better way to duplicate and copy a MongoDB collection?
You can use the "copyDB" database command, which is described at: http://docs.mongodb.org/manual/reference/command/copydb/#dbcmd.copydb In C#, you would run the following on the destination server: var command = new CommandDocument(new BsonElement("copydb", 1), new BsonElement("fromhost", mydbserver), new BsonElement("fromdb", sourcedb), new BsonElement("todb", targetdb)); var client = new MongoClient(mydbserver); var server = client.GetServer(); var db = server.GetDatabase("admin"); db.RunCommand(command);

Categories : C#

Mongodb: How to avoid locking on big collection updates
I think you are confused here, it is not the write lock causing that, it is MongoDB querying for your update documents; the lock does not exist during a page fault (in fact it only exists when actually updating, or rather saving, a document on the disk), it gives way to other operations. The lock is more of a mutex in MongoDB. Page faults on this size of data is perfectly normal, since you obviously do not query this data often, I am unsure what you are expecting to see. I am definitely unsure what you mean by your question: Question: How can I avoid those faults in order to be sure that all my events are correctly updated ? Ok, the problem you may be seeing is that you are getting page thrashing on that machine in turn destroying your IO bandwidth and flooding your working set wi

Categories : Mongodb

what is the best way to create document inside collection in MongoDB
Two main considerations in data modelling for document stores: how data will grow and change over time, and the kinds of queries your application will perform. You have provided info around how data is expected to grow. Just on that basis, I would suggest option #1. { "member_id: 1" , "content_id: 10" , "activity_id: 1" } But, it is also important to understand what kind of queries you will be performing and how you intend to use this data in your application. Additional options possible are: one document per member with an array of feeds in each grouping documents by content or activity id, if that is how your application would query the data. So in summary, to come up with an optimal model, answering question 2 above is also important. PS: Option 2 in your question definite

Categories : PHP



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