94

私は一般的にMongooseとMongoDBにかなり慣れていないので、このようなことが可能かどうかを判断するのに苦労しています。

Item = new Schema({
    id: Schema.ObjectId,
    dateCreated: { type: Date, default: Date.now },
    title: { type: String, default: 'No Title' },
    description: { type: String, default: 'No Description' },
    tags: [ { type: Schema.ObjectId, ref: 'ItemTag' }]
});

ItemTag = new Schema({
    id: Schema.ObjectId,
    tagId: { type: Schema.ObjectId, ref: 'Tag' },
    tagName: { type: String }
});



var query = Models.Item.find({});

query
    .desc('dateCreated')
    .populate('tags')
    .where('tags.tagName').in(['funny', 'politics'])
    .run(function(err, docs){
       // docs is always empty
    });

これを行うためのより良い方法はありますか?

編集

ご迷惑をおかけしましたことをお詫び申し上げます。私がやろうとしているのは、funnyタグまたはpoliticsタグのいずれかを含むすべてのアイテムを取得することです。

編集

where句のないドキュメント:

[{ 
    _id: 4fe90264e5caa33f04000012,
    dislikes: 0,
    likes: 0,
    source: '/uploads/loldog.jpg',
    comments: [],
    tags: [{
        itemId: 4fe90264e5caa33f04000012,
        tagName: 'movies',
        tagId: 4fe64219007e20e644000007,
        _id: 4fe90270e5caa33f04000015,
        dateCreated: Tue, 26 Jun 2012 00:29:36 GMT,
        rating: 0,
        dislikes: 0,
        likes: 0 
    },
    { 
        itemId: 4fe90264e5caa33f04000012,
        tagName: 'funny',
        tagId: 4fe64219007e20e644000002,
        _id: 4fe90270e5caa33f04000017,
        dateCreated: Tue, 26 Jun 2012 00:29:36 GMT,
        rating: 0,
        dislikes: 0,
        likes: 0 
    }],
    viewCount: 0,
    rating: 0,
    type: 'image',
    description: null,
    title: 'dogggg',
    dateCreated: Tue, 26 Jun 2012 00:29:24 GMT 
 }, ... ]

where句を使用すると、空の配列を取得します。

4

6 に答える 6

76

3.2を超える最新のMongoDBでは、ほとんどの場合$lookupの代替として使用できます。これには、結合を「エミュレート」するための実際の「複数のクエリ」.populate()とは対照的に、実際に「サーバー上で」結合を実行するという利点もあります。.populate()

したがって、リレーショナルデータベースがどのようにそれを行うかという意味では、実際には「結合」ではありませ.populate()一方$lookup、オペレーターは実際にサーバー上で作業を行い、多かれ少なかれ「LEFTJOIN」に類似しています。

Item.aggregate(
  [
    { "$lookup": {
      "from": ItemTags.collection.name,
      "localField": "tags",
      "foreignField": "_id",
      "as": "tags"
    }},
    { "$unwind": "$tags" },
    { "$match": { "tags.tagName": { "$in": [ "funny", "politics" ] } } },
    { "$group": {
      "_id": "$_id",
      "dateCreated": { "$first": "$dateCreated" },
      "title": { "$first": "$title" },
      "description": { "$first": "$description" },
      "tags": { "$push": "$tags" }
    }}
  ],
  function(err, result) {
    // "tags" is now filtered by condition and "joined"
  }
)

注意.collection.nameここでは、モデルに割り当てられたMongoDBコレクションの実際の名前である「文字列」に実際に評価されます。mongooseはデフォルトでコレクション名を「複数化」$lookupし、引数として実際のMongoDBコレクション名を必要とするため(サーバー操作であるため)、これはコレクション名を直接「ハードコーディング」するのではなく、mongooseコードで使用する便利なトリックです。 。

配列を使用して不要なアイテムを削除することもできますが、これは、との両方が続くという特別な条件の集約パイプライン最適化$filterにより、実際には最も効率的な形式です。$lookup$unwind$match

これにより、実際には3つのパイプラインステージが1つにまとめられます。

   { "$lookup" : {
     "from" : "itemtags",
     "as" : "tags",
     "localField" : "tags",
     "foreignField" : "_id",
     "unwinding" : {
       "preserveNullAndEmptyArrays" : false
     },
     "matching" : {
       "tagName" : {
         "$in" : [
           "funny",
           "politics"
         ]
       }
     }
   }}

これは、実際の操作が「最初に結合するようにコレクションをフィルタリング」し、次に結果を返し、配列を「巻き戻す」ため、非常に最適です。結果が16MBのBSON制限を超えないように、両方の方法が採用されています。これは、クライアントにはない制約です。

唯一の問題は、特に結果を配列で表示したい場合に、いくつかの点で「直感に反する」ように見えることですが$group、元のドキュメント形式に再構築されるため、ここではそれが目的です。

$lookupまた、現時点では、サーバーが使用するのと同じ最終的な構文で実際に書き込むことができないことも残念です。私見、これは修正すべき見落としです。しかし今のところ、シーケンスを使用するだけで機能し、最高のパフォーマンスとスケーラビリティを備えた最も実行可能なオプションです。

補遺-MongoDB3.6以降

ここに示されているパターンは、他のステージがどのようにロールインされるかによってかなり最適化$lookupされていますが、通常は両方に固有の「LEFT JOIN」$lookupとのアクションが、の「最適な」使用法populate()によって否定されるという点で失敗しています。ここでは、空の配列は保持されません。オプションを追加できますが、これにより、上記の「最適化された」シーケンスが無効になり、通常は最適化で組み合わされる3つのステージすべてがそのまま残ります。$unwindpreserveNullAndEmptyArrays

MongoDB 3.6は、「サブパイプライン」式を可能にする「より表現力豊かな」形式で拡張されます。$lookupこれは、「LEFT JOIN」を保持するという目標を達成するだけでなく、返される結果を減らすための最適なクエリを可能にし、構文を大幅に簡素化します。

Item.aggregate([
  { "$lookup": {
    "from": ItemTags.collection.name,
    "let": { "tags": "$tags" },
    "pipeline": [
      { "$match": {
        "tags": { "$in": [ "politics", "funny" ] },
        "$expr": { "$in": [ "$_id", "$$tags" ] }
      }}
    ]
  }}
])

宣言された「ローカル」値を「外部」値と一致させるために使用されるの$exprは、実際には、MongoDBが元の$lookup構文で「内部的に」実行することです。この形式で表現することにより$match、「サブパイプライン」内で最初の表現を自分で調整できます。

$lookup実際、真の「集約パイプライン」として、他の関連するコレクションへのレベルの「ネスト」を含め、この「サブパイプライン」式内で集約パイプラインを使用して実行できるほぼすべてのことを実行できます。

さらなる使用法は、ここでの質問の範囲を少し超えていますが、「ネストされた母集団」に関しても、の新しい使用パターンにより$lookup、これはほとんど同じであり、完全な使用法では「はるかに」強力です。


実例

以下に、モデルで静的メソッドを使用する例を示します。その静的メソッドが実装されると、呼び出しは単純に次のようになります。

  Item.lookup(
    {
      path: 'tags',
      query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
    },
    callback
  )

または、もう少し現代的なものに拡張すると、次のようになります。

  let results = await Item.lookup({
    path: 'tags',
    query: { 'tagName' : { '$in': [ 'funny', 'politics' ] } }
  })

構造が非常に似て.populate()いますが、実際にはサーバーで結合を行っています。完全を期すために、ここでの使用法は、親と子の両方のケースに従って、返されたデータをマングースドキュメントインスタンスにキャストバックします。

それはかなり些細で、適応するのも簡単で、ほとんどの一般的なケースのようにそのまま使用することもできます。

注意ここでの非同期の使用は、同封の例を簡単に実行するためのものです。実際の実装には、この依存関係はありません。

const async = require('async'),
      mongoose = require('mongoose'),
      Schema = mongoose.Schema;

mongoose.Promise = global.Promise;
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/looktest');

const itemTagSchema = new Schema({
  tagName: String
});

const itemSchema = new Schema({
  dateCreated: { type: Date, default: Date.now },
  title: String,
  description: String,
  tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
});

itemSchema.statics.lookup = function(opt,callback) {
  let rel =
    mongoose.model(this.schema.path(opt.path).caster.options.ref);

  let group = { "$group": { } };
  this.schema.eachPath(p =>
    group.$group[p] = (p === "_id") ? "$_id" :
      (p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` });

  let pipeline = [
    { "$lookup": {
      "from": rel.collection.name,
      "as": opt.path,
      "localField": opt.path,
      "foreignField": "_id"
    }},
    { "$unwind": `$${opt.path}` },
    { "$match": opt.query },
    group
  ];

  this.aggregate(pipeline,(err,result) => {
    if (err) callback(err);
    result = result.map(m => {
      m[opt.path] = m[opt.path].map(r => rel(r));
      return this(m);
    });
    callback(err,result);
  });
}

const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);

function log(body) {
  console.log(JSON.stringify(body, undefined, 2))
}
async.series(
  [
    // Clean data
    (callback) => async.each(mongoose.models,(model,callback) =>
      model.remove({},callback),callback),

    // Create tags and items
    (callback) =>
      async.waterfall(
        [
          (callback) =>
            ItemTag.create([{ "tagName": "movies" }, { "tagName": "funny" }],
              callback),

          (tags, callback) =>
            Item.create({ "title": "Something","description": "An item",
              "tags": tags },callback)
        ],
        callback
      ),

    // Query with our static
    (callback) =>
      Item.lookup(
        {
          path: 'tags',
          query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
        },
        callback
      )
  ],
  (err,results) => {
    if (err) throw err;
    let result = results.pop();
    log(result);
    mongoose.disconnect();
  }
)

async/awaitまたは、追加の依存関係がなく、ノード8.x以降の場合はもう少し最新のものです。

const { Schema } = mongoose = require('mongoose');
const uri = 'mongodb://localhost/looktest';

mongoose.Promise = global.Promise;
mongoose.set('debug', true);

const itemTagSchema = new Schema({
  tagName: String
});

const itemSchema = new Schema({
  dateCreated: { type: Date, default: Date.now },
  title: String,
  description: String,
  tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
});

itemSchema.statics.lookup = function(opt) {
  let rel =
    mongoose.model(this.schema.path(opt.path).caster.options.ref);

  let group = { "$group": { } };
  this.schema.eachPath(p =>
    group.$group[p] = (p === "_id") ? "$_id" :
      (p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` });

  let pipeline = [
    { "$lookup": {
      "from": rel.collection.name,
      "as": opt.path,
      "localField": opt.path,
      "foreignField": "_id"
    }},
    { "$unwind": `$${opt.path}` },
    { "$match": opt.query },
    group
  ];

  return this.aggregate(pipeline).exec().then(r => r.map(m => 
    this({ ...m, [opt.path]: m[opt.path].map(r => rel(r)) })
  ));
}

const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);

const log = body => console.log(JSON.stringify(body, undefined, 2));

(async function() {
  try {

    const conn = await mongoose.connect(uri);

    // Clean data
    await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));

    // Create tags and items
    const tags = await ItemTag.create(
      ["movies", "funny"].map(tagName =>({ tagName }))
    );
    const item = await Item.create({ 
      "title": "Something",
      "description": "An item",
      tags 
    });

    // Query with our static
    const result = (await Item.lookup({
      path: 'tags',
      query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } }
    })).pop();
    log(result);

    mongoose.disconnect();

  } catch (e) {
    console.error(e);
  } finally {
    process.exit()
  }
})()

そして、MongoDB 3.6以降では、$unwind$groupビルドがなくても、次のようになります。

const { Schema, Types: { ObjectId } } = mongoose = require('mongoose');

const uri = 'mongodb://localhost/looktest';

mongoose.Promise = global.Promise;
mongoose.set('debug', true);

const itemTagSchema = new Schema({
  tagName: String
});

const itemSchema = new Schema({
  title: String,
  description: String,
  tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]
},{ timestamps: true });

itemSchema.statics.lookup = function({ path, query }) {
  let rel =
    mongoose.model(this.schema.path(path).caster.options.ref);

  // MongoDB 3.6 and up $lookup with sub-pipeline
  let pipeline = [
    { "$lookup": {
      "from": rel.collection.name,
      "as": path,
      "let": { [path]: `$${path}` },
      "pipeline": [
        { "$match": {
          ...query,
          "$expr": { "$in": [ "$_id", `$$${path}` ] }
        }}
      ]
    }}
  ];

  return this.aggregate(pipeline).exec().then(r => r.map(m =>
    this({ ...m, [path]: m[path].map(r => rel(r)) })
  ));
};

const Item = mongoose.model('Item', itemSchema);
const ItemTag = mongoose.model('ItemTag', itemTagSchema);

const log = body => console.log(JSON.stringify(body, undefined, 2));

(async function() {

  try {

    const conn = await mongoose.connect(uri);

    // Clean data
    await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove()));

    // Create tags and items
    const tags = await ItemTag.insertMany(
      ["movies", "funny"].map(tagName => ({ tagName }))
    );

    const item = await Item.create({
      "title": "Something",
      "description": "An item",
      tags
    });

    // Query with our static
    let result = (await Item.lookup({
      path: 'tags',
      query: { 'tagName': { '$in': [ 'funny', 'politics' ] } }
    })).pop();
    log(result);


    await mongoose.disconnect();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()
于 2017-06-22T00:51:24.387 に答える
40

求めているものは直接サポートされていませんが、クエリが戻った後に別のフィルターステップを追加することで実現できます。

まず、.populate( 'tags', null, { tagName: { $in: ['funny', 'politics'] } } )タグドキュメントをフィルタリングするために必要なことは間違いありません。tags次に、クエリが返された後、入力基準に一致するドキュメントがないドキュメントを手動で除外する必要があります。何かのようなもの:

query....
.exec(function(err, docs){
   docs = docs.filter(function(doc){
     return doc.tags.length;
   })
   // do stuff with docs
});
于 2012-07-10T17:16:46.387 に答える
24

交換してみてください

.populate('tags').where('tags.tagName').in(['funny', 'politics']) 

.populate( 'tags', null, { tagName: { $in: ['funny', 'politics'] } } )
于 2012-07-03T06:57:59.183 に答える
15

更新:コメントを見てください-この回答は質問と正しく一致していませんが、出くわしたユーザーの他の質問に回答している可能性があります(賛成票のためだと思います)ので、この「回答」は削除しません:

最初に:この質問は本当に時代遅れだと知っていますが、私はまさにこの問題を検索し、このSO投稿はGoogleエントリ#1でした。docs.filterそのため、バージョン(受け入れられた回答)を実装しましたが、 mongoose v4.6.0のドキュメントを読んでいると、次のように簡単に使用できます。

Item.find({}).populate({
    path: 'tags',
    match: { tagName: { $in: ['funny', 'politics'] }}
}).exec((err, items) => {
  console.log(items.tags) 
  // contains only tags where tagName is 'funny' or 'politics'
})

これが将来の検索マシンユーザーに役立つことを願っています。

于 2016-09-16T18:26:55.823 に答える
3

最近自分で同じ問題を抱えた後、私は次の解決策を思いつきました:

まず、tagNameが「funny」または「politics」のいずれかであるすべてのItemTagを検索し、ItemTag_idの配列を返します。

次に、tags配列内のすべてのItemTag_idを含むアイテムを検索します

ItemTag
  .find({ tagName : { $in : ['funny','politics'] } })
  .lean()
  .distinct('_id')
  .exec((err, itemTagIds) => {
     if (err) { console.error(err); }
     Item.find({ tag: { $all: itemTagIds} }, (err, items) => {
        console.log(items); // Items filtered by tagName
     });
  });
于 2016-12-07T20:43:48.657 に答える
1

@aaronheckmannの答えは私にとってはうまくいきましたが、populate内に記述された条件と一致しない場合、そのフィールドにはnullreturn doc.tags.length;が含まれているため、に置き換える必要がありました。したがって、最終的なコードは次のとおりです。return doc.tags != null;

query....
.exec(function(err, docs){
   docs = docs.filter(function(doc){
     return doc.tags != null;
   })
   // do stuff with docs
});
于 2017-09-27T21:47:01.320 に答える