まず、私はmongodbにまったく慣れていません。これが、解決策を見つけることができなかった私の質問です。
3 つの異なるコレクションがあるとします。
mongos> show collections
collectionA
collectionB
collectionC
このデータベース内のすべてのコレクションを反復処理し、これらの各コレクションに最後に挿入されたタイムスタンプを見つけるスクリプトを作成したいと考えています。これがmongos内で機能するものです。
var last_element = db.collectionA.find().sort({_id:-1}).limit(1);
printjson(last_element.next()._id.getTimestamp());
ISODate("2014-08-28T06:45:47Z")
1.問題(すべてのコレクションを繰り返す)
sthへの可能性はありますか。お気に入り。
var my_collections = show collections;
my_collections.forEach(function(current_collection){
print(current_collection);
});
ここでの問題、の割り当てがmy_collections
機能しません。私は得るSyntaxError: Unexpected identifier
。「show」ステートメントを引用する必要がありますか? それは可能ですか?
2. 問題 (コレクションを js var に格納する)
これを行うことで、問題 1 を回避できます。
var my_collections = ["collectionA", "collectionB", "collectionC"];
my_collections.forEach(function(current_collection){
var last_element = db.current_collection.find().sort({_id:-1}).limit(1);
print(current_collection);
printjson(last_element.next()._id.getTimestamp());
});
はlast_element.next()
次のエラーを生成します。
エラー hasNext: src/mongo/shell/query.js:124 で false
last_element が正しく保存されていないようです。
私が間違っていることについて何か提案はありますか??
アップデート
ニールの答えは、私をこの解決策に導きます。彼のコードに加えて、関数getTimestamp
が実際に存在するかどうかを確認する必要がありました。一部の「仮想」コレクションでは、_id プロパティがないようです。
db.getCollectionNames().forEach(function(collname) {
var last_element = db[collname].find().sort({_id:-1}).limit(1);
if(last_element.hasNext()){
var next = last_element.next();
if(next._id !== undefined && typeof next._id.getTimestamp == 'function'){
printjson(collname + " >> "+next._id.getTimestamp());
}else{
print(collname + " undefined!! (getTimestamp N/A)")
}
}
});