0

Mongo make an array with date as key ?

[_id] => MongoId Object (
    [$id] => 4fcf2f2313cfcd225700000d
)
[id] => 14
[name] => Aryan Roban
[news] => Array (
    [08-06-2012] => 12
)

Here I want a make news as array with date as key and how to delete a particular key row ?

For example

I want to delete array element with key '08-06-2012' in news array , I dont know the value of it.

Justin John
  • 9,223
  • 14
  • 70
  • 129
  • Isn't the date rather a string? And here is a possible workaround: http://stackoverflow.com/questions/4588303/in-mongodb-how-do-you-remove-an-array-element-by-its-index – YMMD Jun 08 '12 at 09:54
  • date itself.. either date('d-m-Y') or date('Y-m-d') – Justin John Jun 08 '12 at 10:00

2 Answers2

0

Finding Documents won't be a problem, this is very easy. Simply look if news has got a key which matches your search criteria:

db.foo.find({'news.08-06-2012': {'$exists': true}})

Don't forget to put an index on news.

But deleting them is not easily possible. There is another thread which show shows a way to do that, but it's really rather a workaround: In mongoDb, how do you remove an array element by its index Sadly this only works for arrays with numerical indexes and not for associative arrays.

Maybe you could use an own collection for news? Then you could update and delete them easily. Otherwise you could load a full document from your database, manipulate the news in your application and save it afterwards. This would require two datebase queries, but should work.

Community
  • 1
  • 1
YMMD
  • 3,730
  • 2
  • 32
  • 43
  • Is it possible to make array `news.08-06-2012` today, tommorrow I want to add `news.09-06-2012` into same news array. i.e updating the news array every day, but without resetting whole news array... I used the `$set` but it is resetting whole news array – Justin John Jun 08 '12 at 10:23
  • Adding a news is possible using `$set`: `db.foo.update({/*...*/}, {$set: {'news.09-06-2012', 'whatever'}})` (http://www.mongodb.org/display/DOCS/Updating#Updating-%24set) But you cannot easily delete items that way. – YMMD Jun 08 '12 at 10:29
  • If `db.foo.update({/*...*/}, {$inc: {'news.11-06-2012', 1}})`, whether news array will create an new array element as count ? i.e `[11-06-2012] => 1` to existing array – Justin John Jun 08 '12 at 10:44
  • `db.foo.update({/*...*/}, {$unset: {'news.11-06-2012', 1}})` has worked great ... – Justin John Jun 08 '12 at 11:05
  • Awesome! At the end this looks great. :-) – YMMD Jun 08 '12 at 11:34
0

We can use like

db.foo.update({/*...*/}, {$unset: {'news.11-06-2012', 1}})
Justin John
  • 9,223
  • 14
  • 70
  • 129