web-dev-qa-db-ja.com

mongodb / mongoose findMany-IDが配列にリストされているすべてのドキュメントを検索します

_idの配列があり、それに応じてすべてのドキュメントを取得したいのですが、それを行う最善の方法は何ですか?

何かのようなもの ...

// doesn't work ... of course ...

model.find({
    '_id' : [
        '4ed3ede8844f0f351100000c',
        '4ed3f117a844e0471100000d', 
        '4ed3f18132f50c491100000e'
    ]
}, function(err, docs){
    console.log(docs);
});

配列には数百の_idが含まれる場合があります。

200
ezmilhouse

Mongooseのfind関数は、mongoDBに対する完全なクエリです。これは、便利なmongoDB $in句を使用できることを意味します。これは、同じSQLバージョンのように機能します。

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});

このメソッドは、数万のIDを含む配列でもうまく機能します。 ( レコードの所有者を効率的に決定する を参照)

mongoDBで作業している人には、優れた Official mongoDB DocsAdvanced Queries セクションを読むことをお勧めします。

406
Daniel Mendel

この形式のクエリを使用する

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();
8
Derese Getachew

Node.jsとMongoChefの両方で、ObjectIdへの変換が強制されます。これは、DBからユーザーのリストを取得し、いくつかのプロパティを取得するために使用します。 8行目の型変換に注意してください。

// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
        var userIds = [];
        var users = [];         // shortcut to find them faster afterwards
        for (l in list) {       // first build the search array
            var o = list[l];
            if (o.userId) {
                userIds.Push( new mongoose.Types.ObjectId( o.userId ) );           // for the Mongo query
                users[o.userId] = o;                                // to find the user quickly afterwards
            }
        }
        db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
            if (err) callback( err, list);
            else {
                if (user && user._id) {
                    users[user._id].userName = user.fName;
                    users[user._id].userPhotoUrl = user.userPhotoUrl;
                } else {                        // end of list
                    callback( null, list );
                }
            }
        });
    }
4
Nico

IdsはオブジェクトIDの配列です。

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

コールバックでMongooseを使用する:

Model.find().where('_id').in(ids).exec((err, records) => {});

非同期関数でMongooseを使用する:

records = await Model.find().where('_id').in(ids).exec();

実際のモデルでモデルを変更することを忘れないでください。

0
SnnSnn