How to find into mongodb to the last item of an array?

后端 未结 5 1638
无人及你
无人及你 2020-12-29 16:31

I want to find documents where last elements in an array equals to some value. Array elements may be accessed by specific array position:

// i.e. comments[0]         


        
5条回答
  •  天命终不由人
    2020-12-29 16:47

    You can't do this in one go with this schema design. You can either store the length and do two queries, or store the last comment additionally in another field:

    {
        '_id': 'foo';
        'comments' [
            { 'value': 'comment #1', 'by': 'Ford' },
            { 'value': 'comment #2', 'by': 'Arthur' },
            { 'value': 'comment #3', 'by': 'Zaphod' }
        ],
        'last_comment': {
            'value': 'comment #3', 'by': 'Zaphod'
        }
    }
    

    Sure, you'll be duplicating some data, but atleast you can set this data with $set together with the $push for the comment.

    $comment = array(
        'value' => 'comment #3',
        'by' => 'Zaphod',
    );
    
    $collection->update(
        array( '_id' => 'foo' ),
        array(
            '$set' => array( 'last_comment' => $comment ),
            '$push' => array( 'comments' => $comment )
        )
    );
    

    Finding the last one is easy now!

提交回复
热议问题